Android的按键造型编程方式 [英] Android Button Styling Programatically

查看:97
本文介绍了Android的按键造型编程方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何编程添加/删除风格发挥到了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);

这篇关于Android的按键造型编程方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆