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

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

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

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


当前回答

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

其他回答

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

Android文档供参考。

我不相信您可以通过编程方式设置样式。为了解决这个问题,你可以创建一个带有指定样式的模板布局xml文件,例如在res/layout中创建带有以下内容的tvtemplate.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is a template"
        style="@style/my_style" />

然后膨胀这个实例化你的新TextView:

TextView myText = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);

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

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

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

罗曼·盖伊的回答

参考

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

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