【问题标题】:Targeting specific checkbox with tag in listview在列表视图中使用标签定位特定复选框
【发布时间】:2011-05-27 06:45:16
【问题描述】:

在我的应用程序中,我有一个包含行的列表,每行包含一个图像、文本和一个复选框。我覆盖了我的 simpleadapter 的 getView 方法,以根据每个复选框在行中的位置为每个复选框添加一个标签(代码在这里 http://www.heypasteit.com/clip/YME ... bs 和 bs1 是布尔值)。这样我就可以知道调用 onCheckedChanged 时正在更改哪个复选框。但是,我需要手动设置各个复选框的状态。例如,将带有标签“3”的复选框(第 3 行的复选框)的状态设置为“真”。

对此的任何帮助将不胜感激!

【问题讨论】:

    标签: android listview checkbox tags


    【解决方案1】:

    您可以用一组布尔值替换您的方法。例如,如果数组中有 15 个元素,则可以创建一个 boolean[15],并在用户单击复选框时更改不同位置的状态,以及在开始时设置初始状态。

    不是一个完美的例子,但我希望你能明白:

    public class YourActivity extends Activity {
    
    protected boolean[] checkStates;
    
    protected void onCreate(android.os.Bundle savedInstanceState) {
        //... Some of your code where you get a list of you objects
        checkStates = new boolean[list.size()];
        // As an example, let's check some of them:
        checkStates[3] = true;
        checkStates[7] = true;
        //.. Something more
    };
    
    SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.rowsecond, new String[] {"icon", "name"}, new int[] {R.id.image1, R.id.text1}) {
        public View getView(int position, View convertView, ViewGroup parent) {
            final View v = super.getView(position, convertView, parent);
            boxer = (CheckBox)v.findViewById(R.id.checkbox);
            boxer.setTag(position);
            boxer.setOnCheckedChangeListener(checkedChangeListener);
            boxer.setChecked(checkStates[position]);
            return v;
        }
    
        private final OnCheckedChangeListener checkedChangeListener = new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
                final Integer position = (Integer) buttonView.getTag();
                checkStates[position] = isChecked;
            }
        };
    };
    

    }

    如果您尝试从 checkedChangeListener 外部并在初始 onCreate() 方法之后更新复选框状态,请不要忘记调用 yourAdapterInstance.notifyDataSetChanged();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多