【问题标题】:How to programatically set ?android:attr/textAppearanceListItem on a TextView如何以编程方式在 TextView 上设置 ?android:attr/textAppearance 列表项
【发布时间】:2014-08-04 15:15:45
【问题描述】:

我正在尝试在导航抽屉的自定义适配器中设置文本视图的文本外观。我想让一些项目的文本比其他项目小(比如谷歌音乐的导航抽屉)。所以我在 getView 方法中有一个 if 语句,我想对列表项使用默认的 android 样式。

我知道我可以做到以下几点:

textView.setTextAppearance(getContext(), android.R.style.TextAppearance_Small);

但我找不到您可以在 xml 中设置的 textAppearanceListItem 属性的 android.R.style 值:

android:textAppearance="?android:attr/textAppearanceListItem"

【问题讨论】:

    标签: android textview


    【解决方案1】:

    以下代码适用于我:

    textView.setTextAppearance(getContext(), android.R.attr.textAppearanceListItem);
    

    【讨论】:

    • textAppearanceListItem 是否仅适用于 ListView?如果是这样,是否有可用于 RecyclerView 的类似属性?
    • @AJW 评论是针对 cme​​ts 的,不是针对问题的。你有一个问题,好吧,问它,这就是 SO 存在的目的。页面右上角 -> "" ;-)
    • 好吧,我是新手,所以还在学习协议和礼仪。感谢您的反馈,并将使用右上角提出问题。
    • @AJW 当你问“真正的问题”时,你会在这里接触到更多的人(这里的每个人都会很容易看到这个问题,除了帖子的所有者之外,大多数人在 cmets 中看不到问题您发表评论),然后您才能因提出问题和其他用户回答问题而赢得声誉,这就是 SO 上的一切运作方式。
    【解决方案2】:

    setTextAppearance 需要@StyleRes int resId,而android.R.attr.textAppearanceListItemattr,所以它不起作用。

    查看 Android 框架源代码,样式因应用主题而异。以材质主题为例,定义为@style/TextAppearance.Material.ListItem

    https://android.googlesource.com/platform/frameworks/base/+/refs/tags/android-11.0.0_r48/core/res/res/values/themes_material.xml#124

    并且该样式被定义为TextAppearance.Material.Subhead:

    https://android.googlesource.com/platform/frameworks/base/+/refs/tags/android-11.0.0_r48/core/res/res/values/styles_material.xml#498


    所以一种解决方案就是直接使用该样式值:

    textView.setTextAppearance(android.R.style.TextAppearance_Material_Subhead);
    

    或者您可能想根据当前主题解析它的值,这可能更详细:

    TypedValue value = new TypedValue();
    context.getTheme().resolveAttribute(android.R.attr.textAppearanceListItem, value, true);
    textView.setTextAppearance(value.resourceId);
    

    如果你使用 kotlin,splitties-resources 更方便:

    textView.textAppearance = context.resolveThemeAttribute(android.R.attr.textAppearanceListItem)
    

    在此处阅读其文档:https://github.com/LouisCAD/Splitties/blob/v3.0.0/modules/resources/README.md

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-07
      • 2017-10-20
      • 2013-12-28
      • 2011-01-28
      • 1970-01-01
      • 2019-03-27
      • 2011-02-14
      相关资源
      最近更新 更多