单选列表是我们开发过程经常遇到的情况,AlertDialog中可以通过setSingleChoiceItems()方法来实现单选列表。当我们需要动态获取列表内容的时候就经常用到ListView,在ListView中实现单选列表也很简单。系统就给我们封装好了,可以在布局文件中直接设置,android:choiceMode="singleChoice"
,也可以在代码中 listView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
adapter中加载安卓自带的布局simple_list_item_single_choice,这里面包含了一个CheckedTextView,而且也仅仅只有一个实现了Checked接口的TextView,所以通常他都不会满足我们在项目中的需求。
这里采用RadioButton来实现ListView的单选。大家都知道RadioButton的一个特点就是不可以复选,这里就是要利用这个特性吗?肯定不是的,只有在同一组的RadioButton互相之间才会排斥,不同组的RadioButton是毫不相干的。那要怎么做呢,原理也很简单。每次当我们点击一个item中的RadioButton时,记录下这个RadioButton的Id,把上次记录下来的Id代表的RadioButton设置为未选中状态,把此次点击的RadioButton设置为选中状态。下面看一下Adapter的代码。
public class SingleChoiceListViewAdapter extends BaseAdapter {
private String[] strings;
private Activity activity;
private int temp = -1;//记录每次点击的按钮的Id
public SingleChoiceListViewAdapter(Activity activity, String[] strings) {
this.strings = strings;
this.activity = activity;
}
@Override
public int getCount() {
return strings.length;
}
@Override
public Object getItem(int position) {
return strings[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(activity).inflate(R.layout.singlechoicelistviewitem, null);
viewHolder.textView = (TextView) convertView.findViewById(R.id.singlechoice_tv);
viewHolder.radioButton = (RadioButton) convertView.findViewById(R.id.singlechoice_radiobt);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.textView.setText(strings[position]);
**viewHolder.radioButton.setId(position);//把RadioButton的Id设置为position
viewHolder.radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {//如果是选中状态
if (temp != -1) {//temp不为-1,说明已经进行过点击事件
RadioButton tempButton = (RadioButton) activity.findViewById(temp);
if (tempButton != null) {
tempButton.setChecked(false);//取到上一次点击的RadioButton,并设置为未选中状态
}
}
temp = buttonView.getId();//将temp重新赋值,记录下本次点击的RadioButton
}
}
});
if (position == temp) {
viewHolder.radioButton.setChecked(true);//将本次点击的RadioButton设置为选中状态
} else {
viewHolder.radioButton.setChecked(false);
}**
return convertView;
}
final class ViewHolder {
public TextView textView;
public RadioButton radioButton;
}
}
这样就轻松实现了ListView的单选。
源码下载地址:
https://github.com/lulululbj/DailyAndroid
有任何疑问,欢迎加群讨论:261386924