How to dynamically change the color of a button and text on an android

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

+6
source share
5 answers

If you have a button in your main.xml with id = button1, you can use it like this:

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 may have your own form file. Modify it according to your needs.

+11
source

You can change the color of the button text dynamically, as

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

+4
source

Basically you should follow the scheme:

1) get a link to the object you want to change

 findViewById(R.id.<your_object_id>); 

2) apply it to the type of object

 Button btnYourButton = (Button) findViewById(R.id.<your_object_id>); 

3) Use setters on the "btnYourButton" object

4) Redraw your view (possibly calling invalidate ());

It depends on when you want the change to happen. I assume that you will have an eventListener attached to your object, and after the event is fired, you will make your change.

+1
source

You will need some kind of listener in which you listen to the event, and when it changes the color of the shape / text, using some typing methods.

Try:

http://developer.android.com/reference/android/view/View.OnClickListener.html

To give more accurate feedback, I need to know which signal you want to change in order to change the color and shape of the text. Can you give more details on what you mean by dynamic change?

0
source

@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; } 
0
source

Source: https://habr.com/ru/post/900675/


All Articles