Android列表视图中的开关按钮 - 一次只能激活一个开关
创始人
2024-10-08 22:34:22
0

以下是一个例子,展示了如何在Android列表视图中使用开关按钮,并确保一次只能激活一个开关。

首先,创建一个自定义的适配器类,继承自ArrayAdapter:

public class SwitchListAdapter extends ArrayAdapter {
    private int lastSelectedPosition = -1;

    public SwitchListAdapter(Context context, List switchItems) {
        super(context, 0, switchItems);
    }

    @NonNull
    @Override
    public View getView(final int position, View convertView, @NonNull ViewGroup parent) {
        final SwitchItem switchItem = getItem(position);
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
        }

        final Switch switchButton = convertView.findViewById(R.id.switch_button);
        switchButton.setChecked(switchItem.isSelected());

        switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (lastSelectedPosition != -1) {
                        SwitchItem lastSelectedItem = getItem(lastSelectedPosition);
                        if (lastSelectedItem != null) {
                            lastSelectedItem.setSelected(false);
                        }
                    }
                    switchItem.setSelected(true);
                    lastSelectedPosition = position;
                    notifyDataSetChanged();
                } else {
                    switchItem.setSelected(false);
                    lastSelectedPosition = -1;
                }
            }
        });

        return convertView;
    }
}

然后,在XML布局文件中创建一个自定义的列表项布局(例如list_item.xml),其中包含一个Switch按钮:


接下来,使用SwitchListAdapter类创建一个列表视图,并设置适配器:

List switchItems = new ArrayList<>();
// 添加SwitchItem到switchItems列表

SwitchListAdapter adapter = new SwitchListAdapter(this, switchItems);
ListView listView = findViewById(R.id.list_view);
listView.setAdapter(adapter);

这样,你就可以在列表视图中使用开关按钮,并确保一次只能激活一个开关。当选择一个开关时,其他开关将会自动关闭。

相关内容

热门资讯

透视攻略"wepok... 此外,数据分析德州(wepoker免费脚本咨询)辅助神器app还具备辅助透视行为开挂功能,通过对客户...
透视辅助"wpk作弊... 透视辅助"wpk作弊"详细辅助新2025版(黑侠辅助器正版下载神器)是一款可以让一直输的玩家,快速成...
透视规律"wepok... 透视规律"wepoker买钻石有用吗"详细辅助德州论坛(免费透视脚本攻略);1分钟了解详细教程(微信...
透视脚本"wepok... 透视脚本"wepoker透视破解版"详细辅助玩家教你(辅助软件视频神器);实战中需综合运用上述技巧,...
透视真的"wepok... 透视真的"wepoker轻量版有透视吗"详细辅助AI教程(插件攻略)1、不需要AI权限,帮助你快速的...
透视攻略"wepok... 透视攻略"wepoker有脚本吗"详细辅助扑克教程(透视器免费技巧);玩家必备必赢加哟《136704...
透视私人局"wepo... 透视私人局"wepoker开辅助能查到吗"详细辅助AI教程(透视脚本网页辅助),支持语音通讯、好友开...
透视ai"wepok... 透视ai"wepoker有什么规律"详细辅助必备教程(数据分析工具攻略)是一款可以让一直输的玩家,快...
透视教学"wepok... 透视教学"wepoker安装教程"详细辅助攻略教程(轻量版透视方法辅助)准备好在wepoker安装教...
透视app"wepo... 透视app"wepoker买钻石有用吗"详细辅助科技教程(黑侠辅助器正版下载技巧);大神普及一款德州...