我想使一个TextView的内容粗体,斜体和下划线。我尝试了下面的代码,它工作,但没有下划线。

<Textview android:textStyle="bold|italic" ..

我该怎么做?有什么快速的想法吗?


当前回答

只有一行xml代码

        android:textStyle="italic"

其他回答

这是一个添加下划线的简单方法,同时保持其他设置:

textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

您可以通过在其core-ktx依赖项下使用Kotlin的buildSpannedString{}轻松实现。

val formattedString = buildSpannedString {
    append("Regular")
    bold { append("Bold") }
    italic { append("Italic") }
    underline { append("Underline") }
    bold { italic {append("Bold Italic")} }
}

textView.text = formattedString

Programmatialy:

你可以通过编程方式使用setTypeface()方法:

下面是默认字体的代码

textView.setTypeface(null, Typeface.NORMAL);      // for Normal Text
textView.setTypeface(null, Typeface.BOLD);        // for Bold only
textView.setTypeface(null, Typeface.ITALIC);      // for Italic
textView.setTypeface(null, Typeface.BOLD_ITALIC); // for Bold and Italic

如果你想设置自定义字体:

textView.setTypeface(textView.getTypeface(), Typeface.NORMAL);      // for Normal Text
textView.setTypeface(textView.getTypeface(), Typeface.BOLD);        // for Bold only
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);      // for Italic
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC); // for Bold and Italic

XML:

你可以在XML文件中直接设置如下:

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

或者在Kotlin中是这样的:

val tv = findViewById(R.id.textViewOne) as TextView
tv.setTypeface(null, Typeface.BOLD_ITALIC)
// OR
tv.setTypeface(null, Typeface.BOLD or Typeface.ITALIC)
// OR
tv.setTypeface(null, Typeface.BOLD)
// OR
tv.setTypeface(null, Typeface.ITALIC)
// AND
tv.paintFlags = tv.paintFlags or Paint.UNDERLINE_TEXT_FLAG

或者在Java中:

TextView tv = (TextView)findViewById(R.id.textViewOne);
tv.setTypeface(null, Typeface.BOLD_ITALIC);
// OR
tv.setTypeface(null, Typeface.BOLD|Typeface.ITALIC);
// OR
tv.setTypeface(null, Typeface.BOLD);
// OR
tv.setTypeface(null, Typeface.ITALIC);
// AND
tv.setPaintFlags(tv.getPaintFlags()|Paint.UNDERLINE_TEXT_FLAG);

保持简单并在一行中:)

    style="?android:attr/listSeparatorTextViewStyle

通过这种风格,你可以实现下划线