Android - 如何在程序中设置TextView的文本样式?

309
有没有办法以编程的方式设置TextView的textStyle属性?似乎没有setTextStyle()方法。
明确一下,我不是在谈论View/Widget样式!我是在谈论以下内容:
<TextView
  android:id="@+id/my_text"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Hello World"
  android:textStyle="bold" />

1
你可以参考以下链接,并锁定排名第一的答案:https://dev59.com/l2025IYBdhLWcg3wIyKf - Tiep
请检查我的答案在这里。 希望能帮到你。 - Summved Jain
13个回答

520
textview.setTypeface(Typeface.DEFAULT_BOLD);

setTypeface 是 textStyle 属性。

正如 Shankar V 所述,为了保留先前设置的字体属性,可以使用以下代码:

textview.setTypeface(textview.getTypeface(), Typeface.BOLD);

21
应该是 textview.setTypeface(textview.getTypeface(), Typeface.DEFAULT_BOLD); - Sankar V
2
@IlyaEremin 要保留之前设置的字体,你需要这样使用它。 - Sankar V
根据@SankarV的评论修改了我的答案。 - Raz
13
我认为你应该取消 DEFAULT: holder.title.setTypeface(holder.title.getTypeface(), Typeface.BOLD); (注:原文中的“loose”可能是笔误,正确应为“lose”) - Iman Akbari
实际上,textview.getTypeface().getStyle() 就是 android:textStyle - Pierre

176

假设你在values/styles.xml中有一个名为RedHUGEText的样式:

<style name="RedHUGEText" parent="@android:style/Widget.TextView">
    <item name="android:textSize">@dimen/text_size_huge</item>
    <item name="android:textColor">@color/red</item>
    <item name="android:textStyle">bold</item>
</style>

只需在XML布局文件/your_layout.xml中像往常一样创建您的TextView,比如:

<TextView android:id="@+id/text_view_title" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content 
    android:text="FOO" />

在您的Activity的Java代码中,您可以这样做:

TextView textViewTitle = (TextView) findViewById(R.id.text_view_title);
textViewTitle.setTextAppearance(this, R.style.RedHUGEText);

对我而言,这很有效!它应用了颜色、大小、重力等功能。我在使用Android API 8到17级别的手机和平板电脑上使用它没有遇到问题。请注意,截至Android 23版本,该方法已被弃用。上下文参数已被删除,因此最后一行需要更改为:

textViewTitle.setTextAppearance(R.style.RedHUGEText);

为了支持所有API级别,请使用AndroidX TextViewCompat

TextViewCompat.setTextAppearance(textViewTitle, R.style.RedHUGEText)

记住……只有在文本的样式确实取决于您的Java逻辑条件或您正在使用代码“即时”构建UI时,这才是有用的……如果不是这样,最好只需执行以下操作:

<TextView android:id="@+id/text_view_title" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content 
    android:text="FOO" 
    style="@style/RedHUGEText" />

你总是可以按自己的方式去做!


5
这将仅设置在<style>标签中定义的属性子集。 它包括常见的属性(大小、颜色、样式),但不适用于其他属性(包括填充、背景、重力等)。 - karl
7
需要最低API 23吗? - William T. Mallard
5
有两种方法,一种适用于API <23,另一种适用于API 23+。它们看起来完全相同,除了适用于<23的方法需要一个上下文参数,而适用于23+的方法不需要。在幕后,适用于API 23+的方法调用适用于<23的方法并使用TextView的成员上下文。 - MrPlow

69

setTextAppearance在API级别23已被弃用。 - athospy
1
有一个新的 API 23+ 的方法,它不需要上下文参数。 - MrPlow

61

有许多方式可以完成这个任务,以下是其中一些示例:

1.

String text_view_str = "<b>Bolded text</b>, <i>italic text</i>, even <u>underlined</u>!";
TextView tv = (TextView)findViewById(R.id.ur_text_view_id);
tv.setText(Html.fromHtml(text_view_str));

2.

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

3.

SpannableString spannablecontent=new SpannableString(o.content.toString());
spannablecontent.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 
                         0,spannablecontent.length(), 0);
// set Text here
tt.setText(spannablecontent);

4.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="boldText">
        <item name="android:textStyle">bold|italic</item>
        <item name="android:textColor">#FFFFFF</item>
    </style>

    <style name="normalText">
        <item name="android:textStyle">normal</item>
        <item name="android:textColor">#C0C0C0</item>
    </style>

</resources>

 tv.setTextAppearance(getApplicationContext(), R.style.boldText);

或者如果您希望通过XML实现

android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"

setTextAppearance()是我所需要的答案,以便应用在XML中定义的自定义样式。谢谢。 - ashario
在我看来,这是该主题的最佳答案。有许多编程调用代码的选项。 - Nguyen Minh Hien

18

Kotlin 版本

为了保留当前字体和文本样式:

textView.apply {
    setTypeface(typeface, Typeface.NORMAL)
    // or
    setTypeface(typeface, Typeface.BOLD)
    // or
    setTypeface(typeface, Typeface.ITALIC)
    // or
    setTypeface(typeface, Typeface.BOLD_ITALIC)
}

9
这个问题以许多不同的方式在许多地方被问到。我最初在这里回答了它,但我觉得在这个主题中也有相关性(因为我在搜索答案时到达了这里)。
对于这个问题,没有一个一行代码的解决方案,但是这对我的使用情况有效。问题在于“View(context, attrs, defStyle)”构造函数并没有引用实际的样式,而是需要一个属性。所以我们将会:
  1. 定义一个属性
  2. 创建你想要使用的样式
  3. 在我们的主题上为该属性应用样式
  4. 使用该属性创建新的视图实例
在“res/values/attrs.xml”中,定义一个新属性:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="customTextViewStyle" format="reference"/>
    ...
</resources>    

在res/values/styles.xml文件中,我将创建我想要在自定义TextView上使用的样式。

<style name="CustomTextView">
    <item name="android:textSize">18sp</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:paddingLeft">14dp</item>
</style>

在'res/values/themes.xml'或者'res/values/styles.xml'中,修改你的应用程序/活动的主题并添加以下样式:

<resources>
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <item name="@attr/customTextViewStyle">@style/CustomTextView</item>
    </style>
    ... 
</resources>

最后,在您的自定义TextView中,您现在可以使用带有属性的构造函数,并且它将接收您的样式。
public class CustomTextView extends TextView {

    public CustomTextView(Context context) {
       super(context, null, R.attr.customTextView);
    }
}

值得注意的是,我在不同的变体和不同的位置反复使用了 customTextView ,但是视图的名称与样式或属性或任何其他内容匹配并不是必需的。此外,这种技术应该适用于任何自定义视图,而不仅仅是 TextViews。


7

由于setTextAppearance(resId)仅适用于API 23及以上版本,因此请使用:

TextViewCompat.setTextAppearance(textViewGoesHere, resId)

该方法在内部实现如下:

public static void setTextAppearance(@NonNull TextView textView, @StyleRes int resId) {
    if (Build.VERSION.SDK_INT >= 23) {
        textView.setTextAppearance(resId);
    } else {
        textView.setTextAppearance(textView.getContext(), resId);
    }
}

6
这对我很有帮助。
textview.setTypeface(textview.getTypeface(), Typeface.BOLD);

或者
textview.setTypeface(Typeface.DEFAULT_BOLD);

3

我已经用两种简单的方法解决了它。

请按照以下说明操作。

我的现有样式声明:

<style name="SearchInfoText">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textSize">24sp</item>
    <item name="android:textColor">@color/Church_Grey</item>
    <item name="android:shadowColor">@color/Shadow_Church</item>
    <item name="android:shadowRadius">3</item>
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
</style>

我的安卓Java代码:

    TextView locationName = new TextView(getSupportActivity());
    locationName.setId(IdGenerator.generateViewId());
    locationName.setText(location.getName());
    locationName.setLayoutParams(super.centerHorizontal());
    locationName.setTextSize(24f);
    locationName.setPadding(0, 0, 0, 15);
    locationName.setTextColor(getResources().getColor(R.color.Church_Grey));
    locationName.setShadowLayer(3, 1, 1,  getResources().getColor(R.color.Shadow_Church));

问候。


2
您可以尝试这个。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                textView.setTextAppearance(R.style.Lato_Bold);
            } else {
                textView.setTextAppearance(getActivity(), R.style.Lato_Bold);
            }

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