Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

java - Android Button Styling Programmatically

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...