How to change the button text color and button shape(rectangle) dynamically/programmatically?
5 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.

- 19,158
- 5
- 39
- 56
You Can change Button Text Colour dynamically like
Button btnChangeTextColor = (Button)findViewbyId(btnChange); btnChangeTextColor.setTextColor(Color.BLUE);

- 2,886
- 3
- 24
- 31
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.

- 30,580
- 6
- 55
- 83
@Override public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
start_x = event.getX();
start_y = event.getY();
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
setTitle(event.getX() + "y pos" + event.getY());
RelativeLayout layout = (RelativeLayout) findViewById(R.id.lay);
layout.setBackgroundColor(Color.rgb((int) start_x, (int) start_y, 0));
} else if (event.getAction() == MotionEvent.ACTION_UP) {
}
return true;
}

- 3,150
- 28
- 32
You'll need some type of listener where you listen for an event to occur, and when it does change the shape/text color using some set methods.
Try:
http://developer.android.com/reference/android/view/View.OnClickListener.html
To give more pointed feedback I'd need to know what signal you want to have in order to change the text color and shape. Can you give more detail on what you mean by change dynamically?

- 38,547
- 26
- 130
- 141