我想一個複選框添加到該標準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