我试图使用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));

其他回答

我不相信您可以通过编程方式设置样式。为了解决这个问题,你可以创建一个带有指定样式的模板布局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);

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

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

罗曼·盖伊的回答

参考

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

TextView myText = new TextView(new ContextThemeWrapper(MyActivity.this, R.style.my_style));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
    textView.setTextAppearance(R.style.yourStyle)

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

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

Edit:这引用Context对象。