【发布时间】:2014-09-21 11:26:18
【问题描述】:
我很惊讶我在 Stack 上找不到可用的现有答案,所以我在这里。
我有一个 ListFragment,其中包含一个附加到 SimpleCursorAdapter 的列表,该列表由以下 row.xml 文件定义的行组成:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<CheckBox
android:id="@+id/story_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:focusableInTouchMode="false" />
<TextView
android:id="@+id/story"
android:layout_width="wrap_content"
android:layout_height="24sp"
android:lines="1"
android:scrollHorizontally="true"
android:singleLine="true"
android:layout_alignBaseline="@+id/story_check_box"
android:layout_alignBottom="@+id/story_check_box"
android:layout_toRightOf="@+id/story_check_box" />
</RelativeLayout>
我在我的 ListFragment 中使用以下代码将列表与适配器连接起来:
adapter = new SimpleCursorAdapter(getActivity(), R.layout.row, null, new String[] { CProvider.Stories.TITLE }, new int[] { R.id.story }, 0);
setListAdapter(adapter);
然后我尝试在我的片段中使用 CheckBox 来切换所有列表复选框,如下所示:
CheckBox selectAll = (CheckBox) rootView.findViewById(R.id.select_check_box);
selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final ListView listView = getListView();
for(int i=0; i < getListAdapter().getCount(); i++){
View view = getViewByPosition(i, listView);
CheckBox cb = (CheckBox)view.findViewById(R.id.story_check_box);
if (isChecked) {
cb.setChecked(true);
}
else {
cb.setChecked(false);
}
}
}
});
我从这里得到getViewByPosition:Get ListView children that are not in view,几乎可以工作,但是一些复选框没有被选中(并且有一个模式,但我可以似乎没有弄清楚)。它似乎也比我认为必要的更笨拙。
我想要左边的复选框,所以我不想使用checkedtextviews。也许我需要扩展 CursorAdapter 并覆盖 getView?
提前致谢。
【问题讨论】:
-
关于左侧的复选框,请考虑composite view。您也可以让该视图实现
Checkable,这样当它被选中时(通过listView.setItemChecked),您将内部复选框设置为选中。