user9998479
user9998479

Reputation:

set cardview Background logic in Android

i want to when one cardview click event call it's background color change . but i want to only one cardview color change at a time means i click on 1st cardview , color change yellow , but when i click on 2nd cardview change color yellow ,and other all card set color white.

Here is my code :-

btnOpt1.setOnClickListener {
        btnOpt1.setCardBackgroundColor(Color.parseColor("#fcfca9"))
    }

    btnOpt2.setOnClickListener {
        btnOpt2.setCardBackgroundColor(Color.parseColor("#fcfca9"))
    }

    btnOpt3.setOnClickListener {
        btnOpt3.setCardBackgroundColor(Color.parseColor("#fcfca9"))
    }

    btnOpt4.setOnClickListener {
        btnOpt4.setCardBackgroundColor(Color.parseColor("#fcfca9"))
    }

    btnOpt5.setOnClickListener {
        btnOpt5.setCardBackgroundColor(Color.parseColor("##fcfca9"))
    }

enter image description here

Upvotes: 0

Views: 167

Answers (2)

Rohit Sharma
Rohit Sharma

Reputation: 1414

When your button is clicked change white color for rest of the buttons like this

btnOpt1.setOnClickListener {
    btnOpt1.setCardBackgroundColor(Color.parseColor("#fcfca9"));
    btnOpt2.setCardBackgroundColor(Color.parseColor("#ffffff"));
    btnOpt3.setCardBackgroundColor(Color.parseColor("#ffffff"));
    btnOpt4.setCardBackgroundColor(Color.parseColor("#ffffff"));
}

Upvotes: 0

Ravindra Kushwaha
Ravindra Kushwaha

Reputation: 8042

Create the method and pass your view for selected and unselcted

       btnOpt1.setOnClickListener {
          clickCardView(btnOpt1)

        }

Create the method and call from your all click listeners

    private void clickCardView(View btnView){
        btnOpt1.setCardBackgroundColor(Color.parseColor("#ffffff"));
        btnOpt2.setCardBackgroundColor(Color.parseColor("#ffffff"));
        btnOpt3.setCardBackgroundColor(Color.parseColor("#ffffff"));
        btnOpt4.setCardBackgroundColor(Color.parseColor("#ffffff"));

//// main logic is here

    btnView.setCardBackgroundColor(Color.parseColor("#fcfca9"));
    }

Upvotes: 2

Related Questions