RecyclerView在上下文菜单中更改itemView的颜色

时间:2018-11-03 21:32:47

标签: android android-recyclerview adapter contextmenu setbackground

我想使用contextMenu更改recyclerView中itemView的颜色,但是当我单击按钮时,contextMenu更改另一个itemView。

我的适配器类:

public class AdapterGameOne extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<TableOne> list;
private Context context;
public AdapterGameOne(ArrayList<TableOne> list, Context context) {
    this.list = list;
    this.context = context;
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    return new TableOneVH(LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_first_game, parent, false));
}

@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, final int position)  {


  final   TableOneVH    tableOneVH=(TableOneVH)holder;
     TableOne tableOne=list.get(position);
     tableOneVH.textView.setText(tableOne.getName());
     tableOneVH.textView.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
             Log.d("cfc","holv "+holder.getAdapterPosition()+"pos "+position+"myHold "+tableOneVH.getAdapterPosition());
             tableOneVH.itemView.showContextMenu();
         }
     });



}
@Override
public int getItemCount() {
    return list.size();
}
public class TableOneVH extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
    TextView textView;
    RelativeLayout layout;

    public TableOneVH(View itemView) {
        super(itemView);
        layout=itemView.findViewById(R.id.rel);
        textView=itemView.findViewById(R.id.tvForFirstGame);
        itemView.setOnCreateContextMenuListener(this);
    }

    private final MenuItem.OnMenuItemClickListener onEditMenu = new MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {



            switch (item.getItemId()) {
                case 1:


                  itemView.setBackground(ContextCompat.getDrawable(context, R.color.grey));
                    Toast.makeText(context,"adapterPosition= " +getAdapterPosition(),Toast.LENGTH_LONG).show();

                    break;
            }
            return true;
        }
    };
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        MenuItem Grey = menu.add(Menu.NONE, 1, 1, "Grey");
        Grey.setOnMenuItemClickListener(onEditMenu);
    }
}}

例如,我选择第一个项目并尝试更改颜色,结果当我这样做时,我可以看到contextMenu更改了我的项目,而另一个更改了:

enter image description here

0 个答案:

没有答案