关于TextView,如何以编程方式更改样式?

5

例如:

TextView textView = new TextView(PhotoActivity.this);
textView.setText("Photo not found.");

如何设置样式?

textView.set... ???

在Android文档中查看TextView的XML属性,以及相关方法,请在http://developer.android.com/reference/android/widget/TextView.html中检查。 - Tasos
在谷歌上搜索。这是一个过时的问题。 - IntelliJ Amiya
可能是 Android - set TextView TextStyle programmatically? 的重复问题。 - Vishwa
请采纳一个答案,我会回来点赞这个问题;许多人提供了很好的信息。 - PGMacDesign
5个回答

20

如果你想以编程方式为 TextView 添加样式,你需要创建一个继承自 TextAppearance 样式的样式,然后可以使用以下方式应用:

要以编程方式设置 TextView 样式,必须具有继承 TextAppearance 样式的样式,您可以使用以下代码实现:

TextViewCompat.setTextAppearance(statusLinkTextView, R.style.YourTextAppearanceStyle);

8

您可以使用以下选项进行样式设置:

textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setTypeface(null, Typeface.BOLD);
textView.setTypeface(null, Typeface.ITALIC);
textView.setTypeface(null, Typeface.NORMAL);

1
这应该是被接受的答案。它是最简单和有效的。 - caly__pso
4
这会改变字体,而不是样式。 - HBG

6
你可以使用setTextAppearance / setTextAppearance改变TextView的样式。
适用于api级别23以下。
setTextAppearance(int res id)

从api级别23开始

setTextAppearance (Context context, int resId)


TextView textView = new TextView(PhotoActivity.this);
        textView.setText("Photo not found.");
        if (Build.VERSION.SDK_INT > 22) {
            textView.setTextAppearance(PhotoActivity.this, R.style.yourTextViewStyleResourceID);
            /*
            * To give font style Bold Italic I would suggest you check this answer
            * https://dev59.com/l2025IYBdhLWcg3wIyKf#6200841
            * */
        } else {
            textView.setTextAppearance(R.style.yourTextViewStyleResourceID);
        }

更新

不需要检查SDK版本也可以进行样式设置。

TextViewCompat.setTextAppearance(textViewObject, R.style.yourTextViewStyleResourceID);

如果您想要给字体添加加粗斜体样式,我建议您查看这个答案


4
如@JorgeCastillo所指出的,您可以使用TextViewCompat来避免版本检查:TextViewCompat.setTextAppearance(statusLinkTextView,R.style.YourTextAppearanceStyle); 该代码会将文本视图的外观设置为“YourTextAppearanceStyle”样式。 - Beer Me

1

-1
谢谢大家,我找到了我需要的解决方案。
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(AbsListView.LayoutParams.WRAP_CONTENT, AbsListView.LayoutParams.FILL_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.CENTER;

TextView textView = new TextView(PhotoActivity.this);
textView.setText("Photo not found.");
textView.setTextColor(Color.WHITE);
textView.setLayoutParams(params);

另一种选择:

textView.setGravity(Gravity.CENTER);

如果这是您的答案和解决方案,那么问题应该是“如何动态设置文本颜色?”,而不是如何设置样式? - user1140237
在哪个多元宇宙中,"对于TextView,以编程方式更改样式"这句话会导致风格发生变化? - desgraci
答案完全不符合问题。 - Sourav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接