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);
需要对每个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);
}
}
如下使用:
<com.ljfbest.temp.CheckableLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:textAppearance="?android:attr/textAppearanceListItemSmall" />
</com.ljfbest.temp.CheckableLinearLayout>
最后附上效果图