I have a custom ListView
set by an ArrayAdapter
.
Each row has a TextView and 3 RadioButtons.
The objects which populate the AdapterView
look like this:
public class MyItem {
public String title = "";
public boolean rb1 = false;
public boolean rb2 = false;
public boolean rb3 = false;
public MyItem(String title, boolean rb1, boolean rb2, boolean rb3) {
this.title = title;
this.rb1 = rb1;
this.rb2 = rb2;
this.rb3 = rb3;
}
}
Inside the getView()
method, I'm setting a OnLongClickListener
, because I'd like to clear the selection after a long press on a row:
public class MyAdapter extends ArrayAdapter<MyItem> {
private Context context;
private int layoutResourceId;
private ArrayList<MyItem> items = null;
public MyAdapter(Context context, int textViewResourceId, ArrayList<MyItem> objects) {
super(context, textViewResourceId, objects);
this.layoutResourceId = textViewResourceId;
this.context = context;
this.items = objects;
}
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View row = convertView;
final MyItemHolder holder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layoutResourceId, parent, false);
holder = new MyItemHolder();
holder.tvTitle = (TextView) row.findViewById(R.id.tvTitle);
holder.rb1 = (RadioButton) row.findViewById(R.id.rb1);
holder.rb2 = (RadioButton) row.findViewById(R.id.rb2);
holder.rb3 = (RadioButton) row.findViewById(R.id.rb3);
row.setTag(holder);
} else {
holder = (MyItemHolder)row.getTag();
}
String title = items.get(position).title;
Boolean rb1Checked = items.get(position).rb1;
Boolean rb2Checked = items.get(position).rb2;
Boolean rb3Checked = items.get(position).rb3;
holder.tvTitle.setText(title);
holder.rb1.setChecked(rb1Checked);
holder.rb2.setChecked(rb2Checked);
holder.rb3.setChecked(rb3Checked);
row.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
items.get(position).rb1 = false;
items.get(position).rb2 = false;
items.get(position).rb3 = false;
holder.rb1.setChecked(false);
holder.rb2.setChecked(false);
holder.rb3.setChecked(false);
notifyDataSetChanged();
return true;
}
});
return row;
}
static class MyItemHolder {
TextView tvTitle;
RadioButton rb1;
RadioButton rb2;
RadioButton rb3;
}
}
This way it works, BUT... Let's say, the first RadioButton was selected, after a long press on the row, none of the RadioButtons are selected, but I'm unable to select the first one again. I can select the second or third one, but not the first one.