Mahmoud Masri
Mahmoud Masri

Reputation: 1

How to change the color of RecyclerView item, if this item is clicked before?

I have a recyclerView with a custom layout (1 imageView + 2 TextViews)..

The question : The Text of recyclerView item is in Green.. I need to change it to Red , if the user has clicked the item in recyclerView.

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    public TextView title,desc;
    public ImageView thumbnail;

    public MyViewHolder(View view) {
        super(view);
        itemView.setOnClickListener(this);

        title = (TextView) view.findViewById(R.id.text1);
        thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
        desc = (TextView) view.findViewById(R.id.desc);
        whereToGo = title.getText().toString();
    }



    @Override
    public void onClick(View view)
    {


        Intent i = new Intent(mContext, DisplayLockedLesson.class);
        i.putExtra("Lesson Name", title.getText().toString());
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        mContext.startActivity(i);

        }

    }
}

SO, I'm Making Lessons App .. When the user clicked the item of the recyclerView, it changes the color of this item telling the user that he finished the lesson before ...

Thanks .

Upvotes: 0

Views: 2424

Answers (3)

Sharath kumar
Sharath kumar

Reputation: 4132

Create a variable that will store the position of the clicked textview and declare it globally.

private int clickedTextViewPos=-1;

In viewholder whenever position is clicked set that position as clicked and call notifyDataSetChanged()

notifyDataSetChanged() - this notifies the adapter that data is changed.

private class YourViewHolder extends RecyclerView.ViewHolder{

    public YourViewHolder(View itemView) {
    super(itemView);

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

            clickedTextViewPos = getAdapterPosition();
            notifyDataSetChanged();

            }
         });
      }
 }

In the onBindViewHolder if the position is equal show text color in red or else in green.

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

    if(clickedTextViewPos==position){
            edtUser.setTextColor(edtUser.getContext().getResources().getColor(R.color.red));
    }else {
            edtUser.setTextColor(edtUser.getContext().getResources().getColor(android.R.color.green));
    }
}

Upvotes: 4

Apoorv Singh
Apoorv Singh

Reputation: 1335

Inside the model of recyclerview take a boolean isChecked and on basis of that you can set the colour .

Upvotes: 1

Mohammad Aldefrawy
Mohammad Aldefrawy

Reputation: 563

I think you may add a flag to each item either in a hashmap or to a database. Change this flag in the item onclicklistener method...then you can read this flag to change the color of this item.

Upvotes: 1

Related Questions