【问题标题】:setTextAppearance through code referencing custom attribute通过代码引用自定义属性的 setTextAppearance
【发布时间】:2012-01-06 12:24:39
【问题描述】:

我正在使用自定义属性在我的应用程序中实现主题切换。我定义了以下属性:

<resources>
    <attr name="TextAppearance_Footer" format="reference"></attr>
</resources>

我有两个不同地定义这个属性的主题:

<style name="NI_AppTheme.Dark">
    <item name="TextAppearance_Footer">@style/Footer</item>
</style>

@style/Footer 定义如下:

<style name="Footer" parent="@android:style/TextAppearance.Large">
    <item name="android:textColor">#00FF00</item> // Green
</style>

现在,如果我尝试将此样式设置为 TextView,使用:

textView.setTextAppearance(this, R.attr.TextAppearance_Footer);

它不起作用(即不将文本设置为绿色)。但是,如果我通过 xml 指定文本外观:

android:textAppearance="?TextAppearance_Footer"

它工作正常。我能错过什么?我需要设置属性,因为我希望能够在主题之间动态切换。

其他信息:

如果我使用:

textView.setTextAppearance(this, R.style.NI_AppTheme.Dark);

好像没问题。

编辑:经过测试的工作解决方案(感谢 @nininho):

Resources.Theme theme = getTheme();
TypedValue styleID = new TypedValue();
if (theme.resolveAttribute(R.attr.Channel_Title_Style, styleID, true)) {
     channelTitle.setTextAppearance(this, styleID.data);
}

【问题讨论】:

    标签: android


    【解决方案1】:

    为什么不使用:

    textView.setTextAppearance(this, R.style.Footer);
    

    我认为textAppearance必须是一个样式。

    编辑:

    也许你应该试试这个:

    TypedArray a = context.obtainStyledAttributes(attrs,
    new int[] { R.attr.TextAppearance_Footer });
    
    int id = a.getResourceId(R.attr.TextAppearance_Footer, defValue);
    textView.setTextAppearance(this, id);
    

    编辑: 正确的测试代码:

    Resources.Theme theme = getTheme();
    TypedValue styleID = new TypedValue();
    if (theme.resolveAttribute(R.attr.Channel_Title_Style, styleID, true)) {
         channelTitle.setTextAppearance(this, styleID.data);
    }
    

    【讨论】:

    • 因为可能他想通过主题选择这个,而不是直接使用 R.style.Footer。
    • 所以他应该使用主题,但是从问题他不想使用它(不知道为什么)
    • 不确定是不是这样。他试图做的是将 TextAppearance 样式委托给主题。 TextAppearance_Footer 是进行链接的属性,例如,假设您有主题 1 和主题 2。 theme1 会说 TextAppearance_Footer => textAppearance1 和 theme2 会说 TextAppearance_Footer => textAppearance2。在您的小部件中,您只需说 textAppearance => TextAppearance_Footer。你得到的是一个基于当前主题的自动样式链接
    • 好的,所以他会在应用程序清单中使用主题,而不是在此处的代码中使用。因此,为了使其正常工作,他不应该传递 attr id,而是从 attr 获取样式 id 并传递给 setTextAppearance。
    • @aromero 猜对了,就原因而言。我想使用application:theme标签或setTheme为应用程序设置当前选择的主题自动切换textview样式。
    猜你喜欢
    • 2015-07-11
    • 2011-08-29
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    相关资源
    最近更新 更多