以编程方式设置 TextView 的样式 [英] Set style for TextView programmatically

查看:28
本文介绍了以编程方式设置 TextView 的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用具有如下样式的 TextView 构造函数:

I'm trying to use the TextView constructor with style like this:

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

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

However, when I do this, the text view does not appear to take the style (I verified the style by setting it on a static object).

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

I've also tried using myText.setTextAppearance(MyActivity.this, R.style.my_style) but it also doesn't work.

推荐答案

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

I do not believe you can set the style programatically. To get around this you can create a template layout xml file with the style assigned, for example in res/layout create tvtemplate.xml as with the following content:

<?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:

then inflate this to instantiate your new TextView:

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

希望这会有所帮助.

这篇关于以编程方式设置 TextView 的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆