如何改变文本/字体设置在一个Android TextView?

例如,如何使文本加粗?


当前回答

4种方法使Android TextView粗体-完整的答案在这里。

Using android:textStyle attribute <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TEXTVIEW 1" android:textStyle="bold" /> Use bold|italic for bold and italic. using setTypeface() method textview2.setTypeface(null, Typeface.BOLD); textview2.setText("TEXTVIEW 2"); HtmlCompat.fromHtml() method, Html.fromHtml() was deprecated in API level 24. String html="This is <b>TEXTVIEW 3</b>"; textview3.setText(HtmlCompat.fromHtml(html,Typeface.BOLD));

其他回答

在我的情况下,通过string.xml通过html标签传递值..

<string name="your_string_tag"> <b> your_text </b></string> .

在values文件夹中的style.xml文件中定义一个新的样式,使用您想要的格式

<style name="TextViewStyle" parent="AppBaseTheme">
    <item name="android:textStyle">bold</item>
    <item name="android:typeface">monospace</item>
    <item name="android:textSize">16sp</item>
    <item name="android:textColor">#5EADED</item>

</style>

然后通过编写以下带有TextView属性的代码将此样式应用到TextView

style="@style/TextViewStyle"

要在layout.xml文件中这样做:

android:textStyle

例子:

android:textStyle="bold|italic"

程序上的方法是:

setTypeface(Typeface tf)

设置应显示文本的字体和样式。注意,并不是所有字体家族都有粗体和斜体变体,所以你可能需要使用setTypeface(Typeface, int)来获得你真正想要的外观。

在理想的情况下,你应该在你的布局XML定义中设置文本样式属性,就像这样:

<TextView
    android:id="@+id/TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textStyle="bold"/>

通过使用setTypeface方法,有一个简单的方法可以在代码中动态地实现相同的结果。你需要传递一个Typeface类的对象,它将描述TextView的字体样式。因此,要实现与上面XML定义相同的结果,您可以执行以下操作:

TextView Tv = (TextView) findViewById(R.id.TextView);
Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD);
Tv.setTypeface(boldTypeface);

第一行将创建对象表单预定义的样式(在本例中为字体。BOLD,但还有更多预定义的)。一旦我们有了一个字体实例,我们就可以在TextView上设置它。这就是我们的内容将显示在我们定义的样式上。

我希望这对你有很大帮助。欲了解更多信息,请访问

http://developer.android.com/reference/android/graphics/Typeface.html

这是解决方案

TextView questionValue = (TextView) findViewById(R.layout.TextView01);
questionValue.setTypeface(null, Typeface.BOLD);