我想使一个TextView的内容粗体,斜体和下划线。我尝试了下面的代码,它工作,但没有下划线。
<Textview android:textStyle="bold|italic" ..
我该怎么做?有什么快速的想法吗?
我想使一个TextView的内容粗体,斜体和下划线。我尝试了下面的代码,它工作,但没有下划线。
<Textview android:textStyle="bold|italic" ..
我该怎么做?有什么快速的想法吗?
当前回答
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);
保持简单并在一行中:)
如果您正在从文件或网络读取该文本。
你可以通过在文本中添加HTML标签来实现
This text is <i>italic</i> and <b>bold</b>
and <u>underlined</u> <b><i><u>bolditalicunderlined</u></b></i>
然后你可以使用HTML类将HTML字符串处理成可显示的样式文本。
// textString is the String after you retrieve it from the file
textView.setText(Html.fromHtml(textString));
我不知道下划线,但对于粗体和斜体,有“bolditalic”。这里没有提到下划线:http://developer.android.com/reference/android/widget/TextView.html#attr_android:textStyle
请注意,要使用上面提到的粗体,你需要,我引用了那一页
必须为以下常量值中的一个或多个(以'|'分隔)。
你可以用粗体|斜体
你可以检查这个问题的下划线:我可以下划线文本在android布局?
style="?android:attr/listSeparatorTextViewStyle
通过这种风格,你可以实现下划线
这是一个添加下划线的简单方法,同时保持其他设置:
textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);