I want to make a TextView
\'s content bold, italic and underlined. I tried the following code and it works, but doesn\'t underline.
If you are reading that text from a file or from the network.
You can achieve it by adding HTML tags to your text like mentioned
This text is <i>italic</i> and <b>bold</b>
and <u>underlined</u> <b><i><u>bolditalicunderlined</u></b></i>
and then you can use the HTML class that processes HTML strings into displayable styled text.
// textString is the String after you retrieve it from the file
textView.setText(Html.fromHtml(textString));
You can achieve it easily by using Kotlin's buildSpannedString{}
under its core-ktx
dependency.
val formattedString = buildSpannedString {
append("Regular")
bold { append("Bold") }
italic { append("Italic") }
underline { append("Underline") }
bold { italic {append("Bold Italic")} }
}
textView.text = formattedString
This is an easy way to add an underline, while maintaining other settings:
textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
Without quotes works for me:
<item name="android:textStyle">bold|italic</item>
This should make your TextView bold, underlined and italic at the same time.
strings.xml
<resources>
<string name="register"><u><b><i>Copyright</i></b></u></string>
</resources>
To set this String to your TextView, do this in your main.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/register" />
or In JAVA,
TextView textView = new TextView(this);
textView.setText(R.string.register);
Sometimes the above approach will not be helpful when you might have to use Dynamic Text. So in that case SpannableString comes into action.
String tempString="Copyright";
TextView text=(TextView)findViewById(R.id.text);
SpannableString spanString = new SpannableString(tempString);
spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), 0);
spanString.setSpan(new StyleSpan(Typeface.ITALIC), 0, spanString.length(), 0);
text.setText(spanString);
OUTPUT