ListView 實現多選/單選
阿新 • • 發佈:2018-12-06
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>
最後附上效果圖