我想一个复选框添加到该标准AlertDialog室内用一个选择列表添加一个复选框,设置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();
现在,因为它是一个singlechoice,它很好地说明:
我转向使用自定义布局:
<?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没有任何效果。
- 为什么主题变了? (不很重要,只是好奇)编辑看来,主题颜色都搞砸了,当我在项目上点击它的文本颜色为黑“dissapear”入行的背景
请不要在* Android *前加问题的标题,因为它只是增加了噪音,底部的标签绰绰有余。 – Luksprog 2013-03-16 12:52:41