我想用一个选择列表向这个标准 AlertDialog 添加一个复选框
new AlertDialog.Builder(this)
.setSingleChoiceItems(R.array.difficultyLevel_list, 1, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) { level = which; }
})
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
现在,它很好地显示:
我转向使用自定义布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<CheckBox
android:id="@+id/levels_keep"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:checked="false"
android:text="@string/levels_keep" />
<ListView
android:id="@+id/levels_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/difficultyLevel_list"
android:choiceMode="singleChoice" />
</LinearLayout>
使用此代码:
LayoutInflater inflater = getLayoutInflater();
final View customView = inflater.inflate(R.layout.dialog_levels, null);
final ListView list = (ListView) customView.findViewById(R.id.levels_list);
final CheckBox keep = (CheckBox) customView.findViewById(R.id.levels_keep);
// list.setSelected(level);
list.setItemChecked(level, true); // Marks the item as checked
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
level = position;
}
});
new AlertDialog.Builder(this)
.setView(customView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
CheckBox keep = (CheckBox) findViewById(R.id.levels_keep);
if( keep.isChecked() ) {
Context context = PlayersActivity.this;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sp.edit();
editor.putString(context.getString(R.string.pref_level_key), String.valueOf(level));
editor.commit();
}
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
其中显示(列表可滚动):
有几件事我无法弄清楚:
- 为什么我在列表中看不到单选按钮?
如何设置默认选中项?(用解决方案编辑了代码)如何聆听选择的变化?(编辑代码,因为我找到了怎么做)- 如何在复选框方块和复选框文本之间添加填充。我尝试了 android:paddingLeft 但更糟糕的是,文本和正方形重叠。我试过 android:drawablePadding 没有效果。
- 为什么主题变了?(不是很重要,只是好奇)编辑似乎主题颜色都搞砸了,当我点击一个项目时,它的文本颜色变成黑色并“消失”到行的背景中