我要 change color 的 item> item in recyClerview 我单击它时。,但我希望它即使在单击之后保持彩色。
在RecyClerviewAdapter的OnBindViewHolder方法中,我尝试了以下方法:
holder.linearlayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
holder.linearlayout.setBackgroundColor(Color.RED);
}
}
问题是如果我尝试 set color 在OnBindViewHolder方法中,项目保持彩色即使我单击另一个项目,因为在OnBindViewHolder方法中,我只能看到实际项目。
是否可以将所有项目设置为原始状态(没有项目 彩色)并将颜色仅设置为单击的最后一项?
它很简单,只需声明一个全局变量
int mPreviousIndex = -1
然后在您的内部> onclick
holder.linearlayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPreviousInde = position //postition- Position of Adapter
}
}
之后,将其写在您的 onbindviewholder
中if(mPreviousIndex==position){
holder.linearlayout.setBackgroundColor(Color.RED); //color on item selecting item
}
else{
holder.linearlayout.setBackgroundColor(Color.WHITE); //color on item unselecting item
}
这很简单。基本上,我建议您:
- 在适配器中保留您最后一次点击的物品的索引。
- 仅在基于索引的OnBindViewholder(而不是在您的OnClickListener内部)内部进行着色(例如,如果索引具有-1的默认值,则您不着色,如果它具有0 .. count,则您进行着色)
- 在适配器中创建方法a)a)存储上次点击索引在变量b)更新索引中,带有新值c)呼叫notifyItemchanged for Old Index d)呼叫notifyitemchanged for New Index
- 在您的onclicklistener下调用新创建的方法。
我创建了示例RecyclerView
适配器。您可以用LinearLayout
替换TextView
。您应该使用setBackgroundColor()
代替setTextColor()
/**
* 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 indexOfColoredItem = -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) {
indexOfColoredItem = position;
notifyDataSetChanged();
}
});
}
@Override
public int getItemCount() {
return list.size();
}
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));
}
}
}
}