Ultra-Simple Single-choice listview mode SingleMode (custom listview item) and listviewsinglemode
Source: https://stackoverflow.com/questions/8337180/custom-single-choice-listview/12823457#12823457
1. Set in listview item
<span style="font-size:18px;"><RadioButton android:id="@+id/radio1" android:checked="false" android:focusable="false" android:clickable="false" /></span>
Set checked focusable clickable to false
2. Set ListView
<ListView android:id="@android:id/list" android:choiceMode="singleChoice" android:descendantFocusability="beforeDescendants"/>
3. Set in the Custom adapter
int selectedIndex = -1;public void setSelectedIndex(int index){ selectedIndex = index;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) { RadioButton rbSelect = (RadioButton) convertView .findViewById(R.id.radio1); if(selectedIndex == position){ rbSelect.setChecked(true); } else{ rbSelect.setChecked(false); }}
4. Set the onItemClickListener of the list in the activity.
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mChangeAdapter.setSelectedIndex(position); mChangeAdapter.notifyDataSetChanged(); } });
5. Optional. The storage option is in the database. The selected item is still set to the selected status when the selected item is opened for the second time.
ChangeBean bean = mData.get(position); mHolder.tv_name.setText(bean.name); if (selectedIndex == position) { mHolder.iv_choice.setChecked(true); bean.setCheck(true); updateData(bean); } else { mHolder.iv_choice.setChecked(false); bean.setCheck(false); updateData(bean); }
In the activity, set the selected item to the selected state before setAdapter.
mChangeAdapter = new ChangeAdapter(this); mList.setAdapter(mChangeAdapter); initSelect(); mChangeAdapter.refresh(mDatas); addListener(); } private void initSelect() { for (int i = 0; i < mDatas.size(); i++) { if (mDatas.get(i).check){ mChangeAdapter.setSelectedIndex(i); return; } } }