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

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

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

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


当前回答

你可以像这样将ContextThemeWrapper传递给构造函数:

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

其他回答

你可以使用kotlin扩展函数

fun TextView.setStyle(@StyleRes resId: Int) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        setTextAppearance(resId)
    } else {
        setTextAppearance(context, resId)
    }
}

你可以创建一个通用样式,并在多个文本视图上重复使用,如下图所示:

textView.setTextAppearance(this, R.style.MyTextStyle);

Edit:这引用Context对象。

我只使用EditText进行了测试,但您可以使用该方法

setBackgroundResource (int residual)

来应用XML文件中定义的样式。

因为这个方法属于视图,我相信它将适用于任何UI元素。

的问候。

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

Android文档供参考。

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