I have two button in my layout. Also I have different styles defined and I want to set style1 or style 2 for button 1 dynamically and so for button 2. Both buttons are defined in my xml file. I see that there is no way to change the style dynamically in Android. I would like to know if there is a way to get around this issue
Asked
Active
Viewed 146 times
1 Answers
0
Yes, you can do it this way.
private Button testButton1, testButton2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
testButton1 = findViewById(R.id.btn_resource_name1)
testButton2 = findViewById(R.id.btn_resource_name2)
//This is how you set the style:
testButton1.setBackgroundResource(R.drawable.style1);
testButton2.setBackgroundResource(R.drawable.style2);
//Assuming your styles.xml are in drawable directory
}
That's it! Just add any if-else conditions as per your program and don't forget to define your buttons as I've done in above code.

Dharmaraj
- 47,845
- 8
- 52
- 84
-
I tried this.it does change the background but all the text disappears – png Apr 05 '20 at 15:14
-
@png i had tried this code before posting. This works. Just make sure you have typed your text in XML as `android:text="your text"` and it's color matters. When I tried the code my button was Yellow in color but text color of also white so I wasn't able to see text clearly. Make sure you have your `android:textColor` set to a visible color. – Dharmaraj Apr 05 '20 at 15:17
-
@png i would also like if you put your code in the question and some screenshots of output. I will be able to help you more efficiently. – Dharmaraj Apr 05 '20 at 15:18