【问题标题】:how to set the Style Attribute Programmatically in Android?如何在 Android 中以编程方式设置样式属性?
【发布时间】:2011-03-15 20:34:48
【问题描述】:

我必须为以编程方式创建的TextView 设置样式。

如何以编程方式实现style="@style/test"

我已经看过Android developer style documentation,但它没有回答我的问题。有什么想法吗?

【问题讨论】:

标签: android


【解决方案1】:

您可以将样式传递给视图的构造函数。这可以通过两种方式完成:

  1. 使用ContextThemeWrapper 并将您的风格设置为主题:

    ContextThemeWrapper wrappedContext = new ContextThemeWrapper(yourContext, R.style.test);
    TextView testView = new TextView(wrappedContext, null, 0);
    

这里还有一个重要的注意事项 - 要正确设置 ContextThemeWrapper 的样式,我们必须使用三参数构造函数并将 defStyleAttr 参数设置为 0。否则默认按钮样式将应用于视图。

  1. 从 API 21 开始,我们可以使用带有 4 个参数的构造函数:

    View (Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
    

defStyleRes 是您的样式 ID

同理 - defStyleAttr 应该是 0

【讨论】:

    【解决方案2】:
    setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD_ITALIC);
    

    对我有用

    【讨论】:

      【解决方案3】:

      目前不支持动态样式更改。您必须在创建视图之前设置样式(在 xml 中)。

      【讨论】:

      • 我必须使用什么类?
      • 您只需将 style="@style/test" 放在布局 xml 文件中 TextView 的定义中。
      猜你喜欢
      • 2011-01-02
      • 1970-01-01
      • 2021-06-22
      • 2023-01-03
      • 2020-10-06
      • 1970-01-01
      • 2012-08-20
      相关资源
      最近更新 更多