ListView 实现多选/单选

ListView自身带了单选、多选模式,可通过listview.setChoiceMode来设置:
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);//开启多选模式
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);//开启单选模式
listview.setChoiceMode(ListView.CHOICE_MODE_NONE);//默认模式
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);//没用过,不知道用来干嘛的

实现单选
    需要设置:listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 
    ListView控件还需要指定一个selector: android:listSelector="@drawable/checkable_item_selector"

    
    
    
   但是单选选中时的颜色还是系统选中的颜色,而不是自己设定的c1,不知道为什么?

实现多选
    设置:listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 
    需要对每个item的view实现Checkable接口,以下是LinearLayout实现Checkable接口:
public class CheckableLinearLayout extends LinearLayout implements Checkable {
    private boolean mChecked;
    public CheckableLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    @Override
    public void setChecked(boolean checked) {
        mChecked = checked;
        setBackgroundDrawable(checked ? new ColorDrawable(0xff0000a0) : null);//当选中时呈现蓝色
    }
    @Override
    public boolean isChecked() {
        return mChecked;
    }
    @Override
    public void toggle() {
        setChecked(!mChecked);
    }
}
如下使用:

    
 
以下附上demo图:
    ListView 实现多选/单选_第1张图片                                    ListView 实现多选/单选_第2张图片

以下是几个获取/设置 选中条目信息的API:
listview.getCheckedItemCount();//获取选中行数:对CHOICE_MODE_NONE无效
listview.getCheckedItemPosition();//获取选中的某行,只针对单选模式有效,返回int
listview.getCheckedItemIds();//获取选中条目的ids,是long[]类型,注意需要adapter的hasStableIds()返回true,并且这些id是adapter的getItemId(int position)返回的.demo中有演示
listview.setItemChecked(position, value);//设置某行的状态  


另外,使用ListView时可能会报以下错误:
    java.lang.ClassCastException: android.widget.HeaderViewListAdapter cannot be cast to android.widget.SimpleAdapter
ListView有headerView/footerView时,它的原来的Adapter会被封装一下成为HeaderViewListAdapter:

ListAdapter used when a ListView has header views. This ListAdapter wraps another one and also keeps track of the header views and their associated data objects.
This is intended as a base class; you will probably not need to use this class directly in your own code.

可通过以下方式获取原来的Adapter:
    HeaderViewListAdapter hAdapter = (HeaderViewListAdapter) listview.getAdapter();
    MyAdapter my = ( MyAdapter) hAdapter.getWrappedAdapter();

所以,当增加一条header/footer时lv_data.getAdapter()).getWrappedAdapter().getCount()与((HeaderViewListAdapter)listview.getAdapter()).getWrappedAdapter().getCount()是相差1的

Demo地址:
    http://download.csdn.net/detail/ljfbest/8109731

你可能感兴趣的:(—UI)