Search code examples
androidcardviewtextcolor

CardView changes text color when when clicking on another CardView


I'm having a problem when clicking on a CardView. I have a RecyclerView with CardViews where I want to do a single select. First click does it correctly, but when I click on another one the text color of the previous CardView changes to white.

Here is the code for my Adapter:

 holder.setiRecyclerItemSelectedListener(new IRecyclerItemSelectedListener() {
        @Override
        public void onItemSelectedListener(View view, int pos) {
            // Loop all cards in card list
            for (CardView cardView: cardViewList) {
                if (cardView.getTag() == null) // Only available card time slots
                {
                    cardView.setCardBackgroundColor(context.getColor(R.color.colorWhite));
                    holder.txt_time_slot.setTextColor(context.getColor(android.R.color.tab_indicator_text));
                    holder.txt_time_slot_description.setTextColor(context.getColor(android.R.color.tab_indicator_text));
                }
            }

            // Color of selected card time slot
            holder.card_time_slot.setCardBackgroundColor(context.getColor(R.color.colorPrimaryLight));
            holder.txt_time_slot.setTextColor(context.getColor(R.color.colorWhite));
            holder.txt_time_slot_description.setTextColor(context.getColor(R.color.colorWhite));

            // Send broadcast to enable button NEXT
            Intent intent = new Intent(Common.KEY_ENABLE_BUTTON_NEXT);
            intent.putExtra(Common.KEY_TIME_SLOT, position); // Put index of time slot we have selected
            intent.putExtra(Common.KEY_STEP, 3);
            localBroadcastManager.sendBroadcast(intent);
        }
    });

Pictures:

First one does it correctly

First does it correctly

Second one doesn't

Second one doesn't


Solution

  • Define a selected index in adapter:

    int selectedIndex = -1;
    

    You can access child of recyclerView with this method:

    findViewHolderForAdapterPosition(position);
    

    change onClicklistener:

    if (selectedIndex != -1) 
    {
        YourHolder holderOld = (YourHolder) recycleView.findViewHolderForAdapterPosition(selectedIndex);
        holderOld.cardView.setCardBackgroundColor(context.getColor(R.color.colorWhite));
        holderOld.txt_time_slot.setTextColor(context.getColor(android.R.color.tab_indicator_text));
        holderOld.txt_time_slot_description.setTextColor(context.getColor(android.R.color.tab_indicator_text));
    }
    
    selectedIndex = pos;
    holder.card_time_slot.setCardBackgroundColor(context.getColor(R.color.colorPrimaryLight));
    holder.txt_time_slot.setTextColor(context.getColor(R.color.colorWhite));
    holder.txt_time_slot_description.setTextColor(context.getColor(R.color.colorWhite));