Android按钮样式编程 [英] Android Button Styling Programmatically
问题描述
如何以编程方式添加/删除样式到Android按钮?是否可以在运行时应用样式?
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 |
---------- ----------
我想要什么做的是当点击一个按钮时(比如按钮B),它会运行一些代码,然后将按钮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 ||
---------- ==========
我知道如何在XML中做样式(即创建样式),我想知道的是如何在运行时/使用java代码应用样式。
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.
推荐答案
让我们为你做一些代码... :)
为了动态地将样式应用到你的视图(在这种情况下是按钮)你必须在你的布局文件夹(res / layout)中执行以下操作。
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).
我把它命名为, 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>
现在将样式应用于您的按钮,将以下代码添加到您活动的onCreate()方法中。
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);
这篇关于Android按钮样式编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!