我试图使用TextView构造函数的风格像这样:

TextView myText = new TextView(MyActivity.this, null, R.style.my_style);

但是,当我这样做时,文本视图似乎没有采用该样式(我通过在静态对象上设置该样式来验证该样式)。

我还尝试使用myText.setTextAppearance(MyActivity. settextappearance)。this, R.style.my_style),但它也不能工作。


当前回答

您可以在构造函数中设置样式(但样式不能动态更改/设置)。

视图(Context, AttributeSet, int) (int是当前主题中的属性,包含对样式的引用)

罗曼·盖伊的回答

参考

其他回答

不支持动态更改样式。您必须在创建视图之前通过XML设置样式。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
    textView.setTextAppearance(R.style.yourStyle)

当使用可能使用样式继承(或事件可样式属性)的自定义视图时,您必须修改第二个构造函数,以免丢失样式。这对我来说很有效,不需要使用settextappearance ():

public CustomView(Context context, AttributeSet attrs) {
    this(context, attrs, attrs.getStyleAttribute());
}

我们可以使用TextViewCompact。setTextAppearance (textView R.style.xyz)。

Android文档供参考。

参数int defStyleAttr不指定样式。Android文档:

类的当前主题中的属性 样式资源的引用,该样式资源为 视图。可以是0表示不查找默认值。

要在View构造函数中设置样式,我们有两个可能的解决方案:

使用ContextThemeWrapper: ContextThemeWrapper wrappedContext = new ContextThemeWrapper(yourContext, R.style.your_style); TextView TextView = new TextView(wrappedContext, null, 0); 有四个参数的构造函数(从LOLLIPOP开始可用): TextView TextView = new TextView(yourContext, null, 0, r.s yle.your_style);

这两种解决方案的关键是- defStyleAttr参数应该为0,以将我们的样式应用到视图。