Android项目开发经验小结----ListView的单选模式和多选模式

来源:互联网 发布:湖南工业大学网络 编辑:程序博客网 时间:2024/04/28 20:09
最近公司做的一个项目像下面的二级联动功能。

device-2015-11-23-091006.gif
一开始什么都没想,直接就左边RadioGroup右边CheckBox。写完后发现,代码量实在太多了,而且看起来乱糟糟的。
突然想起,ListView的一个xml属性
android:choiceMode="singleChoice"
这个属性可以设置ListView的选择模式。比如单选,多选什么的。
而且这个属性是在ListView的父类AbsListView中的。也就是说,GridView中也有,然后就可以着手实现了。

布局文件。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
 
<include
android:id="@+id/toolbar"
layout="@layout/widget_toolbar_main" />
 
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
 
<ListView
android:background="@color/gray_back"
android:choiceMode="singleChoice"
android:id="@+id/lv_select_sub_and_grade"
android:layout_width="100dp"
android:layout_height="match_parent"/>
 
<GridView
android:choiceMode="multipleChoice"
android:background="@color/normal_white"
android:numColumns="3"
android:listSelector="@drawable/selector_grid_item_select_sub_grade_bg"
android:verticalSpacing="20dp"
android:padding="10dp"
android:id="@+id/gv_select_sub_and_grade"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
 
 
</LinearLayout>
关键属性android:choiceMode,ListView设置为singleChoice(单选模式),GirdView设置为mutipleChoice(多选模式)

单选模式没什么太多需要注意的地方,跟平时的用法一样。一些关于获取当前选中项目的方法
  • isItemChecked(int position)                                  判断一个item是否被选中
  • getCheckedItemCount()                                        获得被选中item的总数
  • setItemChecked(int position, boolean value)     选中一个item
  • clearChoices()                                                          清除选中的item
  • getCheckedItemIds()                                              获取被选中item的id
  • getCheckedItemPosition()                                     获取选中的Item位置,只针对单选模式有效
关于多选模式需要注意的一个点。Item中的布局必须要实现Checkable接口
public class MyLinear extends LinearLayout implements Checkable {
private boolean mChecked;
 
public MyLinear(Context context) {
super(context);
}
 
@Override
public void setChecked(boolean checked) {
mChecked = checked;
setBackgroundColor(mChecked ? getResources().getColor(R.color.blue_white) : getResources().getColor(R.color.dark_blue));
}
 
@Override
public boolean isChecked() {
return mChecked;
}
 
@Override
public void toggle() {
setChecked(mChecked);
}
}

另外,如果布局只有一个TextView的话,可以使用安卓系统提供的一个组件CheckedTextView
简单来说,这个组件就是一个实现了Checkable的一个TextView

关于获取多选模式中的Item
想要获取多选模式中的Item项目,adapter里面就要重写
public boolean hasStableIds() {
return true;
}
而且一定要返回true,然后通过getCheckedItemIds() 就可以获取到相对应Item的position整形数组



0 0
原创粉丝点击