Android Button Styling Programmatically

前端 未结 3 1923
死守一世寂寞
死守一世寂寞 2020-12-15 13:25

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

              


        
相关标签:
3条回答
  • 2020-12-15 14:09

    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.

    0 讨论(0)
  • 2020-12-15 14:15

    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...

    0 讨论(0)
  • 2020-12-15 14:26

    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);
    
    0 讨论(0)
提交回复
热议问题