Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change button and text color dynamically on android

Tags:

android

button

How to change the button text color and button shape(rectangle) dynamically/programmatically?

like image 744
ssk Avatar asked Nov 03 '11 07:11

ssk


People also ask

How can I change the button color in Android?

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.

How do I change the default button color?

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.

What is default color of button in Android?

When I open a new android studio project, the default color for button is purple.


3 Answers

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.

like image 63
Hiral Vadodaria Avatar answered Oct 17 '22 05:10

Hiral Vadodaria


You Can change Button Text Colour dynamically like

Button btnChangeTextColor = (Button)findViewbyId(btnChange); btnChangeTextColor.setTextColor(Color.BLUE);

like image 31
Hitesh Dhamshaniya Avatar answered Oct 17 '22 06:10

Hitesh Dhamshaniya


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.

like image 38
hovanessyan Avatar answered Oct 17 '22 04:10

hovanessyan