首页 > 解决方案 > 如何通过java以键值对的形式在android中添加复选框?

问题描述

我可以通过java在布局中动态添加复选框名称,但是如何像在html中一样添加它的键?复选框(光标)的数据是从数据库中获取的,所以我需要保留它的 id 以便我可以将所选复选框的 id 添加为外键。

protected void onCreate(Bundle savedInstanceState) {
  LinearLayout layout = (LinearLayout) findViewById(R.id.checkboxes);

  while (cursor.moveToNext()) {
      int id = cursor.getInt(cursor.getColumnIndex("id"));
      String name = cursor.getString(cursor.getColumnIndex("name"));

      CheckBox cb = new CheckBox(this);
      cb.setText(name);
      layout.addView(cb);
  }
}

标签: javaandroidxml

解决方案


你可以做一个这样的解决方法:

    while (cursor.moveToNext()) {
        final int id = cursor.getInt(cursor.getColumnIndex("id"));
        String name = cursor.getString(cursor.getColumnIndex("name"));

        CheckBox cb = new CheckBox(this);
        cb.setText(name);
        cb.setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        yourMethodRequiredId(id, isChecked);
                    }
                });
        layout.addView(cb);
    }

推荐阅读