如何通过java在android中以键值对的形式添加复选框?
我可以通过java在布局中动态添加复选框名称,但如何像在html中那样添加其键?复选框(光标)的数据是从数据库中获取的,因此我需要保留其id,以便可以将所选复选框的id添加为外键如何通过java在android中以键值对的形式添加复选框?,java,android,xml,Java,Android,Xml,我可以通过java在布局中动态添加复选框名称,但如何像在html中那样添加其键?复选框(光标)的数据是从数据库中获取的,因此我需要保留其id,以便可以将所选复选框的id添加为外键 protected void onCreate(Bundle savedInstanceState) { LinearLayout layout = (LinearLayout) findViewById(R.id.checkboxes); while (cursor.moveToNext()) {
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);
}
非常感谢你,奥利。你让我开心!!