Switch color buttons after onclick

I have a few buttons. I want, when I click on any of the buttons, its color should be changed, and the other buttons should remain the same. The next time I click on another button, its color should be changed, while others remain unchanged (or in defalut state), and so on. here is my code

switch(v.getId()) { case R.id.bt1: bt11.getBackground().setColorFilter(Color.CYAN,PorterDuff.Mode.Multiple); bt12.setBackgroundResource(android.R.drawable.btn_default); break; case R.id.bt2: bt12.getBackground().setColorFilter(Color.CYAN,PorterDuff.Mode.Multiple); bt11.setBackgroundResource(android.R.drawable.btn_default); break; } 

but when I pressed the bt11 button for the first time, its color becomes CYAN, and when I press bt12, then its color becomes CYAN, and the first button, i.e. bt11, goes into default state, but next time everything goes wrong as both buttons remain in CYAN color

0
source share
3 answers

try this problem in your code is that you put a color filter in the property of the bg button and it will remain even if you change bg, instead set the filter to imgand and set it as bg fr btn

  switch(v.getId()) { case R.id.bt1: Drawable d=b11.getBackground(); d.setColorFilter(Color.CYAN,PorterDuff.Mode.MULTIPLY); b11.setBackgroundDrawable(d); b12.setBackgroundResource(android.R.drawable.btn_default); break; case R.id.bt2: //b2.getBackground().setColorFilter(Color.CYAN,PorterDuff.Mode.MULTIPLY); Drawable dd=b12.getBackground(); dd.setColorFilter(Color.CYAN,PorterDuff.Mode.MULTIPLY); b12.setBackgroundDrawable(dd); b11.setBackgroundResource(android.R.drawable.btn_default); break; } 
0
source

to try

 button.setBackgroundColor( android.graphics.Color.GREEN); 
+1
source

“Next time, everything will not be the same as the buttons remain in the CYAN color,” because when you press another button, you only change the background of the button, but the color remains the same as me. You must also change the background color.

 switch(v.getId()) { case R.id.bt1: bt11.getBackground().setColorFilter(Color.CYAN,PorterDuff.Mode.Multiple); bt12.setBackgroundResource(android.R.drawable.btn_default); bt12.setBackgroundColor(Black); break; case R.id.bt2: bt12.getBackground().setColorFilter(Color.CYAN,PorterDuff.Mode.Multiple); bt11.setBackgroundResource(android.R.drawable.btn_default); bt11.setBackgroundColor(Black); break; } 
0
source

All Articles