如何在 Android 中动态更改按钮样式? [英] How can I change a button style dynamically in Android?

查看:56
本文介绍了如何在 Android 中动态更改按钮样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动态更改按钮的样式,即在 Java 代码中,例如:

I want to change the style of a button dynamically, i.e. in Java code, something like:

((Button)findViewById(id)).setStyle("@styles/foo")

<resources>
    <style name="foo">
        <item name="android:adjustViewBounds">true</item>
        <item name="android:maxHeight">100px</item>
        <item name="android:maxWidth">200px</item>
    </style>
</resources>

我没见过像 setStyle 这样的东西,所以:

I have not seen nothing like setStyle, so:

我必须更改每个属性还是可以更改整个样式?

do I have to change every single property or I can change the whole style?

推荐答案

分配这样的样式

<style name="ButtonHOLO" parent="android:Widget.Button">
      <item name="android:background">@drawable/btn_default_holo_dark</item>
      <item name="android:minHeight">@dimen/calc_btn_h</item>
      <item name="android:minWidth">@dimen/calc_btn_w</item>
      <item name="android:textColor">#ffffff</item>
</style>

动态按钮需要同时使用 setBackgroundResource() 和 setTextAppearance() 函数.例如:

to a button dynamically you need to use both setBackgroundResource() and setTextAppearance() functions. E.g.:

btn.setBackgroundResource(R.drawable.btn_default_holo_dark);
btn.setTextAppearance(context, R.style.ButtonHOLO);

哪里

btn_default_holo_dark

btn_default_holo_dark

是 .xml 文件的名称,用于描述按钮的选择器.

is a name of .xml file which describes a selector for your button.

这篇关于如何在 Android 中动态更改按钮样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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