以编程方式设置 TextView 的样式

新手上路,请多包涵

我正在尝试使用 TextView 构造函数,其样式如下:

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

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

我也尝试过使用 myText.setTextAppearance(MyActivity.this, R.style.my_style) 但它也不起作用。

原文由 Ben 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 506
2 个回答

我不相信您可以以编程方式设置样式。为了解决这个问题,您可以创建一个指定样式的模板布局 xml 文件,例如在 res/layout create 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);

原文由 Dan Kilpatrick 发布,翻译遵循 CC BY-SA 4.0 许可协议

你可以使用扩展函数 kotlin

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

原文由 Alireza Ghanbarinia 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题