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

11

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

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

我已经查看了Android开发者样式文档,但它没有回答我的问题。有什么想法吗?


你可以参考以下 Stack Overflow 上的答案:https://dev59.com/9XA75IYBdhLWcg3wkZ6A#3224365 - a14m
1
现在支持这个了吗? - K Pradeep Kumar Reddy
3个回答

25

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


我需要使用哪个类? - Praveen
你只需要在布局的xml文件中,TextView的定义中加入style="@style/test"即可。 - Robby Pond

5
您可以将样式传递给视图的构造函数。这可以通过两种方式完成:
  1. Use ContextThemeWrapper and setup your style as a Theme for it:

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

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

  1. Starting from API 21 we can use constructor with 4 parameters:

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

其中defStyleRes是您的样式ID

同样需要注意的是 - defStyleAttr 应该为0


3
setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD_ITALIC);

对我来说它有效


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接