我创建了示例RecyclerView适配器。您可以使用View而不是TextView和setAlpha()而不是setTextColor()。你应该在你的片段中触发checkedItem(int)方法然后notifyDataSetChanged或notifyItemChanged()
/** * Created by beyazid on 11.03.2019. */ public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> { private Context context; private LayoutInflater inflater; private ArrayList<String> list; private int indexOfHighlightedItem = -1; public MyAdapter(Context context, ArrayList<String> list) { inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.context = context; this.list = list; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.my_row_for_recycler_view, parent, false); return new MyViewHolder(view); } @Override public void onBindViewHolder(final MyViewHolder holder, final int position) { holder.bindItem(position); holder.tvDummy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { indexOfHighlightedItem = position; notifyDataSetChanged(); } }); } @Override public int getItemCount() { return list.size(); } public void checkedItem(int pos){ indexOfHighlightedItem = pos; } } public class MyViewHolder extends RecyclerView.ViewHolder { TextView tvDummy; public MyViewHolder(View itemView) { super(itemView); tvDummy = itemView.findViewById(R.id.text); } void bindItem(int pos) { String txt = list.get(pos); tvDummy.setText(txt); if(indexOfColoredItem==pos){ tvDummy.setTextColor(ContextCompat.getColor(context, R.color.selectedColor)); } else{ tvDummy.setTextColor(ContextCompat.getColor(context, R.color.yourDefaulColor)); } } } }
您只需创建一个整数即可获得所选位置。喜欢 - private int indexOfHighlightedItem = -1;