我想创建一个复选框列表,这些复选框是从数据库中的表动态生成的,代码可能如下所示:
public void getCategories(Context context) {
Quote quote_instance = new Quote();
final ArrayList<Quote> allQuotesObjects = quote_instance
.getAllObjectsForField(context, "Category");
categories_items = new String[allQuotesObjects.size() - 1];
final boolean[] itemsChecked = new boolean[categories_items.length];
for (int x = 0; x < allQuotesObjects.size() - 1; x++) {
categories_items[x] = allQuotesObjects.get(x).Category;
}
cat_list = new ArrayList<String>(Arrays.asList(categories_items));
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getResources().getString(
R.string.category_widget_label));
builder.setPositiveButton("Select",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < categories_items.length; i++) {
if (itemsChecked[i]) {
categories_ids.add(i);
} else if (categories_ids.contains(i)) {
categories_ids.remove(i);
}
}
}
});
// Log.i("AHMAD", cat_list.toString());
boolean[] prechecked = new boolean[categories_items.length];
Arrays.fill(prechecked, true);
builder.setMultiChoiceItems(categories_items, prechecked,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
itemsChecked[which] = isChecked;
}
});
builder.show();
}
它应该看起来像这张照片 http://i.stack.imgur.com/uc9UR.png (抱歉无法发布图片)
我无法为每个项目创建一个复选框,因为它们是实用生成的。 如何使用共享首选项制作此列表?
答案 0 :(得分:0)
你不能只做一个超过你需要数量的for循环,然后打电话:
Checkbox cb = new Checkbox(getApplicationContext());
cb.(add attributes)
layout.addView(cb)