其实listview自带了属性ChoiceMode,可以用来实现条目的多选。
1.ListView有四种模式
1.public static final int CHOICE_MODE_NONE =
0;
2.public static final int CHOICE_MODE_SINGLE =
1;
3.public static final int CHOICE_MODE_MULTIPLE =
2;
4.public static final int CHOICE_MODE_MULTIPLE_MODAL =
3;
2.istView直接父类AbsListView中,定义了如下公共方法
public boolean isItemChecked(
int position);
public int getCheckedItemCount();
public void setItemChecked(
int position,
boolean value);
public void clearChoices();
3.使用
3.1首先设置ListView模式:
mListView
.setChoiceMode(ListView
.CHOICE_MODE_MULTIPLE)
3.2定义一个adapter,当ListView的某个item被选中之后,将该Item的背景设置为蓝色,以标记为选中。不然虽然ListView知道该item被选中,但是界面上没表现出来。
public View
getView(
int position, View convertView, ViewGroup parent) {
TextView tv;
if (convertView ==
null) {
tv = (TextView) LayoutInflater.
from(mContext).inflate(
android.R.layout.simple_expandable_list_item_1, parent,
false);
}
else {
tv = (TextView) convertView;
}
tv.setText(mStrings[position]);
updateBackground(position , tv);
return tv;
}
@SuppressLint(
"NewApi")
public void updateBackground(
int position, View view) {
int backgroundId;
if (mListView.isItemChecked(position)) {
backgroundId = R.drawable.list_selected_holo_light;
}
else {
backgroundId = R.drawable.conversation_item_background_read;
}
Drawable background = mContext.getResources().getDrawable(backgroundId);
view.setBackground(background);
}
3.3在item每被点击一次中通知adapter,这样做的目的是为了让更新Ui以显示最新的选中状态。(其中mSelectedCount()作用是在actionbar中更新选中的数目)
mListView.setOnItemClickListener(
new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position,
long id) {
mAdapter.notifyDataSetChanged();
updateSeletedCount();
}
});
4.使用ListView的CHOICE_MODE_MULTIPLE_MODAL模式实现多选(参见链接网址)
参考文章:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/1105/1906.html
转载请注明原文地址: https://ju.6miu.com/read-32670.html