Skip to content Skip to sidebar Skip to footer

Recyclerview Setonclicklistener On Textview Changes Background Of Another Row Textview

My RecyclerView is like this When I Clicked on F-0 and S-0 for selection and changed background. It is also changed background color F-15 and S-15. My Code is here. MyRecyclerVie

Solution 1:

onBindViewHolder freely recycles Views used by the adapter.

So if you had: DataObjectHolder X set to View A, and DataObjectHolder Y set to View B and you changed the background for Holder X, it actually changed it on View A, the same view can be then used by Holder Y, showing the wrong background.

So what you need to do, is store the state on DataObjectHolder, and in onBindViewHolder check the state and refresh the background color appropriately.

EDIT:

The ViewHolder:

publicstaticclassDataObjectHolderextendsRecyclerView.ViewHolder
        implementsView
        .OnClickListener {
    TextView label;
    TextView dateTime;
    intlabelColor= Color.RED;
    intdateColor= Color.RED;

    publicDataObjectHolder(View itemView) {
        super(itemView);
        ...
    }

    @OverridepublicvoidonClick(View v) {
        if (v.getId() == label.getId()) {
            labelColor = Color.BLUE;
        } elseif(v.getId() == dateTime.getId()) {
            dateColor = Color.BLUE;
        } else {
            ...
        }
        adapter.notifyDataSetChanged(); 
        // or use notifyItemChanged(pos) if you know the position of the view
    }
}

In the Adapter code:

@Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
    holder.label.setText(mDataset.get(position).getmText1());
    holder.dateTime.setText(mDataset.get(position).getmText2());

    // refresh the background color based on the value stored in holder:
    holder.label.setBackgroundColor(holder.labelColor);
    holder.dateTime.setBackgroundColor(holder.dateColor);
}

Solution 2:

After worked few days on the issue, I have finally solved it before few months. But I was busy with some work. So, I posted it late. Instead of Recyclerview, I have have used Listview. But I think it should also work with Recyclerview. Also, I changed example and put it here. click to view output

Please find code for above example.

MainActivity.Java

package com.example.listviewapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ListViewCompat;
import android.util.Log;
import android.widget.ListView;
import java.util.ArrayList;

publicclassMainActivityextendsAppCompatActivity {

private ListView listView;
ContentAdapter contentAdapter;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    listView = (ListView)findViewById(R.id.listview);
    contentAdapter = newContentAdapter(getApplicationContext(),R.layout.row_layout);
    listView.setAdapter(contentAdapter);
    for (intindex=0; index < 60; index++) {
        Contentcontent=newContent(index+1,"A-" + index,
                "B-" + index,"C-"+index);
        contentAdapter.add(content);
        contentAdapter.notifyDataSetChanged();
    }
  }
}

ContentAdapter.java

Please make sure that ContactHoder declare as final.

package com.example.listviewapplication;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;

publicclassContentAdapterextendsArrayAdapter{
    ArrayListlist=newArrayList();
    private HashMap mIdToPosition;

    publicContentAdapter(Context context, int resource) {
        super(context, resource);

        init();

    }
    privatevoidinit() {
        mIdToPosition = newHashMap();
    }


    publicvoidadd(Content object) {
        super.add(object);
        list.add(object);
    }

    @OverridepublicintgetCount() {
        //return super.getCount();return list.size();
    }

    @Overridepublic Object getItem(int position) {
        //return super.getItem(position);return list.get(position);
    }


    @Overridepublic View getView(finalint position, final View convertView, final ViewGroup parent) {

        View row;
        row = convertView;

        final ContactHolder contactHolder;

        if(row == null){
            LayoutInflaterlayoutInflater= (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.row_layout,parent,false);
            contactHolder = newContactHolder();
            contactHolder.tx_data1 = (TextView)row.findViewById(R.id.tx_data1);
            contactHolder.tx_data2 = (TextView)row.findViewById(R.id.tx_data2);
            contactHolder.tx_data3 = (TextView)row.findViewById(R.id.tx_data3);

            row.setTag(contactHolder);

        }else{
            contactHolder = (ContactHolder)row.getTag();
        }

        Contentcontent= (Content) this.getItem(position);
        //get DataId as unique value, it is set from MainActivity for loopIntegerdataId= content.getDataId();
        contactHolder.tx_data1.setText(content.getData1());
        contactHolder.tx_data1.setTag(dataId+"-"+content.getData1()+"-"+position+"-1");
        contactHolder.tx_data2.setText(content.getData2());
        contactHolder.tx_data2.setTag(dataId+"-"+content.getData2()+"-"+position+"-2");
        contactHolder.tx_data3.setText(content.getData3());
        contactHolder.tx_data3.setTag(dataId+"-"+content.getData3()+"-"+position+"-3");


        //check hashmap key (dataId) for already data is in listview or not//if textview was selected then check which textview is selected otherwise all textview has default colorif(mIdToPosition.containsKey(dataId)){
            Log.d("containsKey",mIdToPosition.get(dataId).toString());
            Stringx= mIdToPosition.get(dataId).toString();
            String[] newarr = x.split("-");
            Integermid= Integer.parseInt(newarr[0]);
            Integerpos= Integer.parseInt(newarr[3]);
            Integertextid= Integer.parseInt(newarr[4]);
            //Set Default Color for all textviews//            contactHolder.tx_data1.setBackgroundResource(R.color.colorPrimaryDark);//            contactHolder.tx_data2.setBackgroundResource(R.color.colorPrimaryDark);//            contactHolder.tx_data3.setBackgroundResource(R.color.colorPrimaryDark);//check textview id and accordingly set color for selected textviewswitch (textid) {
                case1:
                    contactHolder.tx_data1.setBackgroundResource(R.color.colorAccent);
                    contactHolder.tx_data1.setSelected(true);
                    break;
                case2:
                    contactHolder.tx_data2.setBackgroundResource(R.color.colorAccent);
                    contactHolder.tx_data2.setSelected(true);
                    break;
                case3:
                    contactHolder.tx_data3.setBackgroundResource(R.color.colorAccent);
                    contactHolder.tx_data3.setSelected(true);
                    break;
            }

        }
        else{
            contactHolder.tx_data1.setBackgroundResource(R.color.colorPrimaryDark);
            contactHolder.tx_data2.setBackgroundResource(R.color.colorPrimaryDark);
            contactHolder.tx_data3.setBackgroundResource(R.color.colorPrimaryDark);
        }


        //Set OnclickListner for all Textviews
        View.OnClickListeneronClickListener=newView.OnClickListener() {
            @OverridepublicvoidonClick(View v) {
                Strings= v.getTag().toString();
                String[] arr = s.split("-");

                //if textview already selected then unselect and set default color of textview.if(v.isSelected()){
                    v.setBackgroundResource(R.color.colorPrimaryDark);
                    v.setSelected(false);
                    mIdToPosition.remove(Integer.parseInt(arr[0]));
                }else{
                    switch (v.getId()){
                        case R.id.tx_data1:
                            v.setBackgroundResource(R.color.colorAccent);
                            v.setSelected(true);
                            //Store dataId key in  hashmap (DataId is unique id)
                            mIdToPosition.put(Integer.parseInt(arr[0]),s);
                            contactHolder.tx_data2.setBackgroundResource(R.color.colorPrimaryDark);
                            contactHolder.tx_data3.setBackgroundResource(R.color.colorPrimaryDark);
                            break;

                        case R.id.tx_data2:
                            v.setBackgroundResource(R.color.colorAccent);
                            v.setSelected(true);
                            //Store dataId key in  hashmap (DataId is unique id)
                            mIdToPosition.put(Integer.parseInt(arr[0]),s);
                            contactHolder.tx_data1.setBackgroundResource(R.color.colorPrimaryDark);
                            contactHolder.tx_data3.setBackgroundResource(R.color.colorPrimaryDark);
                            break;

                        case R.id.tx_data3:
                            v.setBackgroundResource(R.color.colorAccent);
                            v.setSelected(true);
                            //Store dataId key in  hashmap (dataId is unique id)
                            mIdToPosition.put(Integer.parseInt(arr[0]),s);
                            contactHolder.tx_data1.setBackgroundResource(R.color.colorPrimaryDark);
                            contactHolder.tx_data2.setBackgroundResource(R.color.colorPrimaryDark);
                            break;
                    }
                }
            }
        };

        contactHolder.tx_data1.setOnClickListener(onClickListener);
        contactHolder.tx_data2.setOnClickListener(onClickListener);
        contactHolder.tx_data3.setOnClickListener(onClickListener);

        return row;
    }

    staticclassContactHolder{
        TextView tx_data1, tx_data2, tx_data3;
    }

}

Content.java

package com.example.listviewapplication;


publicclassContent {

    privateString data1,data2,data3;
    privateInteger dataId;

    publicContent (Integer dataId,String data1,String data2,String data3){
        this.setData1(data1);
        this.setData2(data2);
        this.setData3(data3);
        this.setDataId(dataId);
    }

    publicStringgetData1() {
        return data1;
    }

    publicvoidsetData1(String data1) {
        this.data1 = data1;
    }

    publicStringgetData2() {
        return data2;
    }

    publicvoidsetData2(String data2) {
        this.data2 = data2;
    }

    publicStringgetData3() {
        return data3;
    }

    publicvoidsetData3(String data3) {
        this.data3 = data3;
    }

    publicIntegergetDataId(){
        return dataId;
    }

    publicvoidsetDataId(Integer dataId){
        this.dataId = dataId;
    }

}

Please let me know, if any one required further assistance on it.

Post a Comment for "Recyclerview Setonclicklistener On Textview Changes Background Of Another Row Textview"