您的位置:首页 > 其它

ListView如何实现单选,默认选中一条。

2015-09-24 16:09 711 查看
首先,我要实现的功能是加载数据时,默认选中一行数据,整个ListView只能有一个RadioButton为选中状态。

public View getView(final int position1, View convertView,
ViewGroup parent) {
ViewHolder holder = null;
View view = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.music_list_adapter,
null);
holder = new ViewHolder();
holder.radioButton = (RadioButton) convertView
.findViewById(R.id.item_cb_section);
holder.tv_sectionname = (TextView) convertView
.findViewById(R.id.tv_zxing_sectionname);
convertView.setTag(holder);
} else {
view = convertView;
holder = (ViewHolder) view.getTag();
}
holder.tv_sectionname.setText(csList.get(position1).toString());
final RadioButton radio = (RadioButton) convertView
.findViewById(R.id.item_cb_section);
holder.radioButton = radio;
if (position1 == mIndex) {
holder.radioButton.setChecked(true);
} else {
holder.radioButton.setChecked(false);
}
return convertView;
}


getView方法中这里的的position1,是每一行的下标,比如说listview中有3条数据,那么对应的position1就是0,1,2 这里 你只需要判断position1等于0的话,就可以实现默认第一行的radioButton为选中状态了,我这里是用mIndex是因为我需要保存用户选中的选中,好让用户下次进入这个listview中显示之前用户勾选的item。那么如何实现单选呢,你直接就可以在底下加一个else,判断当前加载的数据的下标即position1是否为你让它选中的下标,不是的话 ,设置为false;这样就轻松实现单选,默认选中了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: