以编程方式设置 Android 按钮样式 [英] Android Button Styling Programmatically

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

问题描述

如何以编程方式向 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屋!

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