实现listview右侧单选框

ListView实现的列表勾选,勾选后进行缓存,下次启动时勾选上次退出时勾选项。

具体效果如下图所示:

001

在MainActivity中设置listview的监听,点击条目后,缓存当前选中项并进行页面重绘。

1
2
3
4
5
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
saveCurrentPosition(position);
adapter.notifyDataSetChanged();
}

PhoneSettingListAdapter的构造函数,将上下文和需要填充的数据传递过来:

1
2
3
4
public PhoneSettingListAdapter(Context context, List<String> list) {
this.context = context;
this.list = list;
}

PhoneSettingListAdapter的getView方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.item_phone_list, null);
holder.tv = (TextView) convertView.findViewById(R.id.tv_phone_category);
holder.iv = (ImageView) convertView.findViewById(R.id.iv_phone_chosen);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
String content = list.get(position);
holder.tv.setText(content);
//缓存的选中位置
int CurrentPosition = Integer.parseInt(getCurrentPosition());
//当前位置是选中位置
if (CurrentPosition == position) {
convertView.setSelected(true);
convertView.setPressed(true);
holder.iv.setImageResource(R.drawable.ic_single_check);
}
//当前不是选中位置
else {
convertView.setSelected(false);
convertView.setPressed(false);
holder.iv.setImageResource(R.drawable.ic_single_empty);
}
return convertView;
}

activity、adapter中代码和布局文件就不一一贴出来了。

样例项目上传了github:https://github.com/cuibin1991/Listview_ChoiceMode