Reputation: 2368
How do you programmatically add/remove style to an android button? Is it possible to apply the styling at runtime?
I have two buttons that look like these
---------- ---------- | Button A | | Button B | ---------- ----------
what i wanted to do is when a button is clicked (lets say Button B), it runs some code, then changes the style of button B to something else (i.e highlighted borders) and will be something like this:
---------- ========== | Button A | || Button B || ---------- ==========
I know how to do the styling(i.e create the style) in XML, all I want to know is how to apply the styles on runtime/using java code.
Upvotes: 5
Views: 26686
Reputation: 16329
As I answered in this other thread, you could either set the background programatically as some folks suggest, or you could set the style programatically (as I suggest here) if you are using the support library.
Upvotes: 0
Reputation: 6332
Let's do some code for you case...:) For applying style to your view (button in this case) dynamically is you have to do the following in your layout folder (res/layout).
I named it as,buttonstyle.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<solid android:color="#449def"/>
<stroke android:width="1dp" android:color="#2f6699"/>
<corners android:radius="3dp"/>
<padding android:left="10dp" android:top="10dp" android:right="10dp"
android:bottom="10dp"/>
</shape>
</item>
<item>
<shape>
<gradient android:startColor="#449def" android:endColor="#2f6699" android:angle="270"/>
<stroke android:width="1dp" android:color="#2f6699"/>
<corners android:radius="4dp"/>
<padding android:left="10dp" android:top="10dp" android:right="10dp"
android:bottom="10dp"/>
</shape>
</item>
</selector>
Now apply style to your button, add the following code to onCreate() method of your activity..
Button transferBtn = new Button(this);
transferBtn.setText("Test Example");
transferBtn.setId(R.string.transferBtn);
transferBtn.setBackgroundResource(R.layout.buttonstyle);
Upvotes: 12
Reputation: 10518
You can't apply xml-defined styles in runtime (from code). If you want to change background and font style when button is clicked (pressed) you should create selector which defines what background to use for normal button or for clicked state.
If selector is not what you want, you should manually set every button property to desired value via button's setXXX method of Button class.
P.S. You can swap old button for a new another one inflated from xml with different style. But this is not a good way I suppose...
Upvotes: 3