java - 如何通过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);
}
}
解决方案
你可以做一个这样的解决方法:
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);
}
推荐阅读
- python - 在查询过滤器中使用日期范围
- python-3.x - 为什么我的 n 体模拟没有产生轨道(使用围绕太阳的地球和金星)?
- yii2 - Yii2 mpdf,将图像添加到PDF文件的第二页
- python - Python:在两个日期之间创建 numpy 数组
- java - 如何在同一个 Reporter 中收集所有 dropwizard 指标?
- python - 带有可选参数的 zip()
- prebid - 如何在 Android Prebid sdk 中为 OpenX、Criterio 和 Rubicon 添加适配器
- react-native - React-native-elements 将所有图标显示为方形
- javascript - EaselJS:检查形状是否绘制在画布上的其他形状内
- grails - 使用 Spock 模拟真实对象的功能