我可以通过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);
}
}
最佳答案
您可以采取如下解决方法:
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);
}
关于java - 如何通过java以键值对的形式在android中添加复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52345466/