How to change the button text color and button shape(rectangle) dynamically/programmatically?
To set Android Button background color, we can assign android:backgroundTint XML attribute for Button in layout file with the required Color Value. To programmatically set or change Android Button background color, we may call pass the method Button.
Android Colored Buttons The Colored Button takes the color of the colorAccent attribute from the styles. xml file. Change the color of colorAccent to one of your choice to get the desired background color. Now, there are two important attributes to style a button : colorButtonNormal : The normal color of the button.
When I open a new android studio project, the default color for button is purple.
If you have a button in your main.xml with id=button1 then you can use it as follows:
setContentView(R.layout.main);
Button mButton=(Button)findViewById(R.id.button1);
mButton.setTextColor(Color.parseColor("#FF0000")); // custom color
//mButton.setTextColor(Color.RED); // use default color
mButton.setBackgroundResource(R.drawable.button_shape);
R.drawable.button_shape(button_shape.xml):
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#70ffffff"
android:centerColor="#70ffffff"
android:endColor="#70ffffff"
android:angle="270" />
<corners
android:bottomRightRadius="8dp"
android:bottomLeftRadius="8dp"
android:topLeftRadius="8dp"
android:topRightRadius="8dp"/>
</shape>
You can have your own shape file.change it according to your need.
You Can change Button Text Colour dynamically like
Button btnChangeTextColor = (Button)findViewbyId(btnChange); btnChangeTextColor.setTextColor(Color.BLUE);
Basically you have to follow the scheme:
1) get reference to the object you want to change
findViewById(R.id.<your_object_id>);
2) cast it to the object type
Button btnYourButton = (Button) findViewById(R.id.<your_object_id>);
3) Use setters on the object "btnYourButton"
4) Redraw your View (possibly calling invalidate());
It depends when do you want the change to happen. I assume you will have an eventListener attached to your object, and after the event is fired you will perform your change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With