我试图使用TextView构造函数的风格像这样:
TextView myText = new TextView(MyActivity.this, null, R.style.my_style);
但是,当我这样做时,文本视图似乎没有采用该样式(我通过在静态对象上设置该样式来验证该样式)。
我还尝试使用myText.setTextAppearance(MyActivity. settextappearance)。this, R.style.my_style),但它也不能工作。
我试图使用TextView构造函数的风格像这样:
TextView myText = new TextView(MyActivity.this, null, R.style.my_style);
但是,当我这样做时,文本视图似乎没有采用该样式(我通过在静态对象上设置该样式来验证该样式)。
我还尝试使用myText.setTextAppearance(MyActivity. settextappearance)。this, R.style.my_style),但它也不能工作。
当前回答
不支持动态更改样式。您必须在创建视图之前通过XML设置样式。
其他回答
我不相信您可以通过编程方式设置样式。为了解决这个问题,你可以创建一个带有指定样式的模板布局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);
你可以使用kotlin扩展函数
fun TextView.setStyle(@StyleRes resId: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
setTextAppearance(resId)
} else {
setTextAppearance(context, resId)
}
}
我们可以使用TextViewCompact。setTextAppearance (textView R.style.xyz)。
Android文档供参考。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
textView.setTextAppearance(R.style.yourStyle)
你可以创建一个通用样式,并在多个文本视图上重复使用,如下图所示:
textView.setTextAppearance(this, R.style.MyTextStyle);
Edit:这引用Context对象。