sachit
sachit

Reputation: 1138

switching color of buttons after onclick

i have several buttons.i want when i click on any of the buttons its color should be changed and other buttons should remain the same.Next time when i click on other button its color should be change and other remain the same(or in by 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 button bt11 very first time its color becomes CYAN and when i press bt12 then its color becomes CYAN and the first button i.e bt11 comes in its default state but next time everything is going wrong both the buttons remain in the CYAN color

Upvotes: 0

Views: 1358

Answers (3)

Athul Harikumar
Athul Harikumar

Reputation: 2491

try this the problem in your code is you are putting a color filter on the button's bg property and it will remain even if you change the bg instead set the filter on the imgand 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;
    }

Upvotes: 0

Braj
Braj

Reputation: 2162

"next time everything is going wrong both the buttons remain in the CYAN color" because when you click other button, you are only changing other button background but color remained the same I guess. You have to change background color also.

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;
}

Upvotes: 0

Anil Olakkal
Anil Olakkal

Reputation: 3894

try

button.setBackgroundColor( android.graphics.Color.GREEN);

Upvotes: 1

Related Questions