代碼中使用 myLV.setChoiceMode(SINGLE_CHOICE_MODE) 編譯報錯:can't find symbol SINGLE_CHOICE_MODE。
SINGLE_CHOICE_MODE 不是 ListView 或 AbsListView 的常量,正確常量為 CHOICE_MODE_SINGLE。
ListView myLV = findViewById(R.id.ListView1);
// 正確常量
myLV.setChoiceMode(ListView.CHOICE_MODE_SINGLE); // 單選
// 或
myLV.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
// 其他可用模式
myLV.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); // 多選
myLV.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); // 多選模態
myLV.setChoiceMode(ListView.CHOICE_MODE_NONE); // 無選擇
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice" />
Item 佈局使用 CheckedTextView 可自動顯示選中狀態:
<CheckedTextView xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:paddingStart="16dp"
android:paddingEnd="16dp" />
ListView 選擇模式常量為 CHOICE_MODE_* 系列,定義在 AbsListView 中,注意區分舊版錯誤常量名。