最终效果图如下:
![](https://img-blog.csdn.net/20130810135447468?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdGlhbnRpYW5zaGFuZ2NoYQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
apiDemo中有一个listView实现多选的例子
比较简单
- package com.example.android.apis.view;
-
- import android.app.ListActivity;
- import android.os.Bundle;
- import android.widget.ArrayAdapter;
- import android.widget.ListView;
-
- /**
- * This example shows how to use choice mode on a list. This list is
- * in CHOICE_MODE_MULTIPLE mode, which means the items behave like
- * checkboxes.
- */
- public class List11 extends ListActivity {
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- setListAdapter(new ArrayAdapter<String>(this,
- android.R.layout.simple_list_item_multiple_choice, GENRES));
-
- final ListView listView = getListView();
-
- listView.setItemsCanFocus(false);
- listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
- }
-
-
- private static final String[] GENRES = new String[] {
- "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
- "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
- };
- }
利用了framework中的布局 simple_list_item_multiple_choice.xml ,该布局内容就是一个CheckedTextView
- <CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@android:id/text1"
- android:layout_width="match_parent"
- android:layout_height="?android:attr/listPreferredItemHeight"
- android:textAppearance="?android:attr/textAppearanceLarge"
- android:gravity="center_vertical"
- android:checkMark="?android:attr/listChoiceIndicatorMultiple"
- android:paddingLeft="6dip"
- android:paddingRight="6dip"
- />
在实际的应用中我们肯定会遇到复杂布局的情况,一旦使用复杂布局,发现listview原生的多选模式失效了!失效原因通过查看ListView的源码可以发现,问题出在setupChild函数中
- private void setupChild(View child, int position, int y, boolean flowDown,int childrenLeft, boolean selected, boolean recycled) {
- ..................
- if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null) {
- if (child instanceof Checkable) {
- ((Checkable) child).setChecked(mCheckStates.get(position));
- }
- }
- }
其中的child对象就是自定义adapter的getView()函数的返回结果,由于我们没有实现Checkable接口所以无法操作。变通办法,ListView有一个察看item是否被选中的函数,结合该函数,修改自定义adapter的getView函数:
- public View getView(int position, View convertView, ViewGroup parent) {
- boolean check = ((ListView)parent).isItemChecked(position);
- viewHolder.myCheckedTextView.setChecked(check);
- }