带有开关按钮的 ListView,setChecked on 启动两个开关,并保存另一个开关的状态

ListView with switch buttons, setChecked on start two switches, and save state of another

我有两个问题:

我想要实现的是一个列表视图,每行都有一个切换按钮,它工作正常,但我想在第 4 个和第 5 个开始时设置为 True

holder.s.setChecked(位置==4);

holder.s.setChecked(位置==5);

设置为true only only the 5th,如何做到这一点,请给我任何提示?

第二个问题:在滚动我的列表视图时改变开关按钮的状态,我尝试了很多教程但没有运气,如何保持开关按钮的状态?

 @Override
public View getView(final int position, View convertView, ViewGroup parent) {
    final ViewHolder holder;
    String pytanie = getItem(position);


    if (convertView==null){
        convertView = inflater.inflate(R.layout.cardio_row, null);
        holder = new ViewHolder();
        holder.question = (TextView) convertView.findViewById(R.id.question);
        holder.s = (Switch)convertView.findViewById(R.id.switch1);
        convertView.setTag(holder);
    }
    else{
        holder = (ViewHolder) convertView.getTag();
    }
    //Model_cardio question = getItem(position);
    holder.question.setText(pytanie);
    holder.s.setChecked(position == 4);
    holder.s.setChecked(position == 5);
    holder.s.setTag(position);


    return convertView;
}

编辑: 我已经添加了这个,并且想在一些列表中存储一个状态

  holder.s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        }
    });

在你的代码中,两个语句

holder.s.setChecked(position == 4);
holder.s.setChecked(position == 5);

一个接一个执行。对于每个位置。

所以对于位置号 4,第一个语句导致 Switch 被检查,只是在下面的语句中再次被取消检查。

你可以引入一个boolean变量:

boolean doCheck = (position == 4) || (position == 5);
holder.s.setChecked(doCheck);

问题中比较棘手的部分是如何跟踪已检查的列表行。 为此,你需要一种像

这样的List
ArrayList<Integer> checkedRows;

在适配器的构造函数中,您可以根据需要初始化列表。

checkedList = new ArrayList();
// if you like, you can add rows 4 and 5 as checked now
// and drop the respective code in 'getView()':
checkedList.add(4);
checkedList.add(5);

然后在 getView() 方法中,检查每个 View:

holder.s.setTag(position);
holder.s.setOnCheckedChangeListener(null);

if (checkedList.contains(position) )
{
    holder.s.setChecked(true);
}
else
{
    holder.s.setChecked(false);
}

holder.s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            if (isChecked )
            {
                checkedList.add((Integer)buttonView.getTag() );
            }
            else
            {
                checkedList.remove((Integer)buttonView.getTag() );
            }
        }
};