【问题标题】:How do I apply a style programmatically?如何以编程方式应用样式?
【发布时间】:2011-02-19 15:52:29
【问题描述】:

我有一个名为 Red 和 Green 的样式,我有一个 if 语句来确定要应用哪个样式,但我不知道实际应用来自 java 的样式的代码。

【问题讨论】:

标签: android


【解决方案1】:

这个问题没有单一的解决方案,但这适用于我的用例。问题是,'View(context, attrs, defStyle)' 构造函数不引用实际样式,它需要一个属性。所以,我们会:

  1. 定义一个属性
  2. 创建您想要使用的样式
  3. 在我们的主题上应用该属性的样式
  4. 使用该属性创建视图的新实例

在'res/values/attrs.xml'中,定义一个新属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="customTextViewStyle" format="reference"/>
    ...
</resources>    

在 res/values/styles.xml' 我将创建我想在我的自定义 TextView 上使用的样式

<style name="CustomTextView">
    <item name="android:textSize">18sp</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:paddingLeft">14dp</item>
</style>

在 'res/values/themes.xml' 或 'res/values/styles.xml' 中,为您的应用程序/活动修改主题并添加以下样式:

<resources>
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <item name="customTextViewStyle">@style/CustomTextView</item>
    </style>
    ... 
</resources>

最后,在您的自定义 TextView 中,您现在可以使用带有属性的构造函数,它将接收您的样式。在这里,而不是总是

public class CustomTextView extends TextView {

    public CustomTextView(Context context, int styleAttribute) {
        super(context, null, styleAttribute);
    }

    // You could also just apply your default style if none is given
    public CustomTextView(Context context) {
        super(context, null, R.attr.customTextViewStyle);
    }
}

使用所有这些组件,您现在可以执行 if/else 语句以在运行时以您喜欢的样式生成新视图

CustomTextView ctv;
if(useCustomStyles == true){
    ctv = new CustomTextView(context, R.attr.customTextViewStyle);
}else{
    ctv = new CustomTextView(context, R.attr.someOtherStyle);
}

值得注意的是,我在不同的变体和不同的地方反复使用了customTextView,但绝不要求视图的名称与样式或属性或任何内容匹配。此外,这种技术应该适用于任何自定义视图,而不仅仅是 TextViews。

【讨论】:

  • 对我来说使用&lt;item name="@attr/customTextViewStyle"&gt; 不起作用,我必须删除@attr 才能工作,所以它只是&lt;item name="customTextViewStyle"&gt;
【解决方案2】:

可以使用 setTextAppearance(context, resid) 方法以编程方式将样式应用于 TextView。 (样式的resId可以在R.style.YourStyleName中找到)

【讨论】:

    【解决方案3】:

    我发现只有在从 Java 内部创建视图时才能做到这一点。如果事先在 XML 中定义,则无法动态更改样式。

    【讨论】:

    • 这如何回答你自己的问题?
    • 这不是一个正确的答案。即使您在 xml 中设置了可绘制对象,您也可以通过编程方式覆盖它。
    【解决方案4】:

    您可以使用全新的 Paris 库以编程方式应用样式:

    Paris.style(yourView).apply(condition ? R.style.Green : R.style.Red);
    

    唯一需要注意的是,并非所有属性都受支持(但很多属性都受支持,并且可以通过为库做出贡献而相当容易地添加支持)。

    免责声明:我是图书馆的原作者。

    【讨论】:

    • 到目前为止,这应该被标记为答案!
    猜你喜欢
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多