0

我正在实现一个 Android 应用程序,其中有一个列表视图。这个列表视图的每个元素都有一个切换按钮,并且使用扩展 BaseAdapter 的自定义适配器,我设法获得了哪些切换按钮被选中,哪些没有被选中。但是,如果我想对这些切换按钮施加约束怎么办?假设当我检查第二个切换按钮时,我希望第一个也自动检查。我应该怎么做?谢谢

       public class MyCustomAdapter<T> extends BaseAdapter {
Context mContext; //the application context
LayoutInflater mInflater; //object that is used to set the layout of the View
ArrayList<T> mList; //list of the items shown in the user interface
SparseBooleanArray mSparseBooleanArray; //object that is used to keep track of the selected items of the list

ToggleButton[] toggleButtons;

public MyCustomAdapter(Context context, ArrayList<T> list) {

    this.mContext = context;
    mInflater = LayoutInflater.from(mContext);
    mSparseBooleanArray = new SparseBooleanArray();
    mList = new ArrayList<T>();
    this.mList = list;
    toggleButtons = new ToggleButton[list.size()];
}
public View getView (int position, View convertView, ViewGroup parent) {

    if(convertView == null) {
        convertView = mInflater.inflate(R.layout.list_item_with_toggle, null);
    }

    toggleButtons[position] = (ToggleButton)convertView.findViewById(R.id.toggleEnable);


    switch (position){

        case 0:
            toggleButtons[position].setOnCheckedChangeListener(new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    Toast.makeText(mContext, ""+0, Toast.LENGTH_SHORT).show();
                }
            });
            break;
        case 1:                
            toggleButtons[position].setOnCheckedChangeListener(new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    //Toast.makeText(mContext, ""+isChecked, Toast.LENGTH_SHORT).show();
                    if(isChecked) {
                        if(!toggleButtons[0].isChecked()) {
                           // Toast.makeText(mContext, "elemento 1 "+toggleButtons[1].isChecked(), Toast.LENGTH_SHORT).show();
                            toggleButtons[0].setChecked(true);


                        } else {
                            //things to do if toggleButtons[0] == true
                        }
                    } else {
                      //things to do if isChecked == false
                    }

                }
            });
            break;
        default:
              break;
    }

    return convertView;
}
}
4

1 回答 1

1

大概你有一个代表列表中每一行的某种对象,如果是这样,你可以尝试这样的事情:

  • 将链接项目的列表/数组添加到您的对象并在适用的情况下填充它。
  • 单击按钮时,更新链接的项目。
  • 调用notifyDataSetChanged()并强制重绘列表。
于 2014-10-27T13:01:46.377 回答