【发布时间】:2017-10-05 20:44:24
【问题描述】:
我在一个带有复选框的 android 应用程序中有一个列表视图,我正在尝试获取已检查项目的列表。我已经尝试使用 setChecked(true) 在 getView() 方法中设置检查状态,并通过点击该项目手动检查它。我尝试了两种不同的方法来获取选中的项目,并且都返回 null。我做错了什么?
格雷格
//Called from a menu
//First attempt - checked is always null
//I also set setChoiceMode = CHOICE_MODE_MULTIPLE before setting adapter
//and set no setChoiceMode
String ItemsChecked = null;
ListView listview = (ListView) findViewById(R.id.ListLists);
SparseBooleanArray checked = listview.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
if (checked.get(i)) {
ItemsChecked += Integer.toString(i) + ",";
}
}
//I then tried this and checked[] is empty
//I also set setChoiceMode = CHOICE_MODE_NONE before setting adapter
long checked[] = listview.getCheckedItemIds();
for (int i = 0; i < checked.length; i++) {
ItemsChecked += "" + checked[i] + ",";
}
//Layout for the ListView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/icon"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginLeft="4dp"
android:layout_marginStart="4dp"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:layout_marginTop="4dp"
android:src="@drawable/ic_listit" >
</ImageView>
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@+id/label"
android:textSize="22sp" >
</TextView>
</LinearLayout>
【问题讨论】: