Android Programmatically apply style to your view
Applying style to your view (button in this case) dynamically is pretty easy.
All you have to do is place the following in your layout folder (res/layout)
Let's call this file : 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>
Next to apply style to your button, add the following code to onCreate() method of your activity
Button transferBtn = new Button(this);
transferBtn.setText("Transfer");
transferBtn.setId(R.string.transferBtn);
transferBtn.setBackgroundResource(R.layout.buttonstyle);
That should be it!
Comments