我想让我的按钮在recyclerView中可切换,这意味着当单击彼此时都应该被选中

时间:2019-07-20 07:40:53

标签: android

当我单击一个按钮时,应取消选择其他按钮来实现此目的

我在堆栈中看到了其他答案,但没有一个解决我的问题,或者我无法正确理解

public class LocationAreaAdapter extends RecyclerView.Adapter<LocationAreaAdapter.ViewHolder> {

   private int  mSelectedItem = -1;
    private ArrayList<String> mNames = new ArrayList<>();
    private Context mContext;
    private ArrayList<Boolean> isChecked=new ArrayList<>();

    private AdapterView.OnItemClickListener onItemClickListener;

    public LocationAreaAdapter(Context context,ArrayList<String> mNames ){

        this.mContext=context;
        this.mNames=mNames;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.locatin_area_cardview, viewGroup, false);
        return new ViewHolder(view,this);
    }


    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int i) {

                    holder.name.setText(mNames.get(i));
                    holder.name.setChecked(i == mSelectedItem);

                   //what to do here
                            }


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

    public void onItemHolderClick(ViewHolder holder) {
        if (onItemClickListener != null)
            onItemClickListener.onItemClick(null, holder.itemView, holder.getAdapterPosition(), holder.getItemId());
    }

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

        RadioButton name;
        LocationAreaAdapter mAdapter;
        public ViewHolder(View itemView, final LocationAreaAdapter mAdapter) {
            super(itemView);
            this.mAdapter = mAdapter;
            name = itemView.findViewById(R.id.location_area_button);
            itemView.setOnClickListener(this);
            name.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
            mSelectedItem = getAdapterPosition();
            notifyItemRangeChanged(0, mNames.size());
            mAdapter.onItemHolderClick(ViewHolder.this);
        }
    }
    }

当我单击按钮时,未单击按钮,而是recyclerview闪烁

1 个答案:

答案 0 :(得分:1)

当单击查看器项时,请选择当前位置,然后取消选择其他查看器位置:

  holder.name.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            mSelectedItem = position;
            notifyDataSetChanged();
        }
    });



  if (mSelectedItem==position ) {
             //viewHolder.item.setVisibility(View.VISIBLE);
               show itew here.
    } else {
       // viewHolder.item.setVisibility(View.GONE);
          hideitew here.
    }