我在Fragment中有一个列表视图,您可以在其中检查项目,以及一个显示单击项目的按钮。但是当我取消选中项目并按下按钮时,它仍然显示为已选中。什么可以解决问题?
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.feat, container, false);
final ListView list=(ListView)view.findViewById(R.id.listView1);
final Button button=(Button)view.findViewById(R.id.button1);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list.setItemChecked(4, true);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_multiple_choice,items);
list.setAdapter(adapter);
SparseBooleanArray checked = list.getCheckedItemPositions();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.button1:
SparseBooleanArray a = list.getCheckedItemPositions();
if (checked(a) > 0) {
String vCheckedList = "";
for (int i = 0; i < list.getAdapter().getCount(); i++) {
if (a.valueAt(i) && i < list.getAdapter().getCount() && a.size() > 1)
vCheckedList += list.getAdapter().getItem(a.keyAt(i)) + "\n";
else if (a.valueAt(i))
vCheckedList += list.getAdapter().getItem(a.keyAt(i));
}
Toast.makeText(getActivity().getApplicationContext(), vCheckedList + " is checked", Toast.LENGTH_SHORT).show();
a.clear();
} else
Toast.makeText(getActivity().getApplicationContext(), "No Item is Selected", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
});
return view;
}
这是xml:`
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="382dp">
</ListView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:id="@+id/button1"
android:layout_gravity="center_horizontal|bottom" />
答案 0 :(得分:0)
在xml文件中设置CheckBox
android:clickable="true"
android:focusable="false"
答案 1 :(得分:0)
删除onClick()中的a.clear();
方法然后它将起作用。