代码之家  ›  专栏  ›  技术社区  ›  Praveen

如何在Android中以编程方式设置样式属性?

  •  9
  • Praveen  · 技术社区  · 14 年前

    我必须为 TextView 它是以编程方式创建的。

    我如何实施 style="@style/test" 以编程方式?

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

    3 回复  |  直到 8 年前
        1
  •  25
  •   Robby Pond    14 年前

    当前不支持动态样式更改。在创建视图之前必须设置样式(XML)。

        2
  •  3
  •   kleopatra Aji kattacherry    12 年前
    setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD_ITALIC);
    

    它对我有用

        3
  •  2
  •   DmitryArc    8 年前

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

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

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

    重要提示-正确设置样式 上下文主题包装 我们必须使用三参数构造函数和集合 defStyleAttr 参数为0。否则,默认按钮样式将应用于视图。

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

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

    在哪里? defStyleRes 是你的风格ID吗

    具有相同的备注-defstyleattr应为0