how to update data in recyclerview item from another item?

你。 提交于 2020-01-06 06:08:34

问题


I have a problem with RecyclerView, I have RecyclerView which has a radio button and few other views in each row item,

What I wanted exactly is, when a RadioButton is checked by user I want to uncheck other RadioButton(if anything is checked earlier). Since it is a Recyclerview I cannot use radiogroup.

In the adapter onBindViewHolder I write this listener for each radio button

  holder.radioButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectedPosition = holder.getAdapterPosition();
            Toast.makeText(activity, "section: " + selectedPosition, Toast.LENGTH_SHORT).show();
        }
    });

how can i make previous radio button selected uncheck?
in other words, how can i update view property in specific item of recyclerview from another item view listener?


回答1:


You need to have a reference to the selectedItem globally in your adapter and then update all the items when the user checks a new radio button.

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
    private int selectedItemPosition = -1;
}

And do things in your onBindViewHolder() method of the adapter,

@Override
public void onBindViewHolder(final Adapter.ViewHolder holder, int position) {
    holder.radioButton.setChecked(holder.getAdapterPosition()==selectedItemPosition);
    holder.radioButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectedItemPosition = holder.getAdapterPosition();
            notifyDataSetChanged();
        }
    });
}



回答2:


Try this::

        if (position == selectedPosition) {
            holder.radioButton.setChecked(true);
            Toast.makeText(activity, "section: " + selectedPosition, Toast.LENGTH_SHORT).show();
        } else {
            holder.radioButton.setChecked(false);
        }

        holder.radioButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectedPosition = holder.getAdapterPosition();
                notifyDataSetChanged();
            }
        });


来源:https://stackoverflow.com/questions/47864758/how-to-update-data-in-recyclerview-item-from-another-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!