Change background color of circular button android

2020-02-15 06:36发布

问题:

I have a button in android which I have made circular in shape. Also I have an xml which changes the background color on pressed, but the color goes back to normal after the pressed state is changed.

I made the following change to code

arg0.setBackgroundColor(getResources().getColor(R.color.greenText));

But now the background takes rectangular shape and not the oval shape.

回答1:

Okay as you have said the background shape changes when using setBackgroundColor, i think here's what you want,

1.you might be interested in color filters like this

Button btn = (Button) findViewById(R.id.button1);
btn.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xFFAA0000));

You use different values according to your required colour.If you want to know the constant values of colours, you can refer the documents.

2.you can programmatically set the shade of the entire button using the PorterDuff multiply mode. This will change the button colour rather than just the tint.

For example for a red shaded button

btn.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);

For a green shaded button

btn.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);

And so on.What it actually does is, it works by multiplying the current button colour value by your colour value.

3.You can also use an online tool like this Android Button Maker to customize your button and use android:background="@drawable/custom_btn" in your layout(inside the tag) to define the customized button.

Now i believe there are more ways to achieve what you want but i think these are some easy and quick fixes you can use.Hope this helps.