-1

My RecyclerView contains radio buttons. when I click one my following implementation should deselect all the others (notifyDataSetChanged() should rebind all the rows). Surprisingly, onClick is never triggered:

public class NameAdapter extends RecyclerView.Adapter<NameAdapter.NameHolder> {

    private List<String> myNames;
    private int selectedPosition = -1;

    public NameAdapter(List<String> names) {
        myNames = names;
    }

    @Override public NameHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        View view = LayoutInflater.from(context).inflate(R.layout.name_item, parent, false);
        return new NameHolder(view);
    }

    @Override public void onBindViewHolder(NameHolder holder, int position) {
        String name = myNames.get(position);
        holder.name.setText(name);
        holder.radioButton.setChecked(position == selectedPosition);
    }

    @Override public int getItemCount() {
        return myNames.size();
    }

    public class NameHolder extends RecyclerView.ViewHolder {

        private TextView    name;
        private RadioButton radioButton;

        public NameHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.name);
            radioButton = (RadioButton) itemView.findViewById(R.id.radio_button);
            View.OnClickListener clickListener = new View.OnClickListener() {
                @Override public void onClick(View v) {
                    selectedPosition = getAdapterPosition();
                    notifyDataSetChanged();
                }
            };
            itemView.setOnClickListener(clickListener);
        }
    }
}
rmunn
  • 34,942
  • 10
  • 74
  • 105
user3148156
  • 168
  • 1
  • 1
  • 13
  • I can try http://stackoverflow.com/questions/24471109/recyclerview-onclick?rq=1 but my main concern was why doesn't setting the listener on the item work? – user3148156 Nov 20 '15 at 07:47
  • Your code seems to work fine in my emulator. Then again, I had to write my own Activity, so maybe your problem is not with the adapter class – Bö macht Blau Nov 20 '15 at 07:49

1 Answers1

0

Use one of the following way to trigger click event.

public class NameHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    private TextView name;
    private RadioButton radioButton;

        public NameHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.name);
            radioButton = (RadioButton) itemView.findViewById(R.id.radio_button);
            itemView.setOnClickListener(this);
        }
        @Override
        public boolean onClick(View v) {
            //Put your code here 
        }
    }
Chirag Savsani
  • 6,020
  • 4
  • 38
  • 74