Android的按键造型编程方式按键、造型、方式、Android

2023-09-06 06:24:24 作者:你是我心里说不出的痛

你如何编程添加/删除风格发挥到了Android的按钮?是否有可能适用的造型在运行时?

How do you programatically 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),它运行约code,然后更改按钮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 code应用样式上运行/

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.

推荐答案

让我们做一些$ C $下你的情况下... :) 对于应用样式到您的视图(在这种情况下键),动态是你必须做你的布局文件夹下(RES /布局)。

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>

现在应用样式的按钮,添加以下code到的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);