How to set the font style to bold, italic and underlined in an Android TextView?

前端 未结 11 544
借酒劲吻你
借酒劲吻你 2020-12-02 04:04

I want to make a TextView\'s content bold, italic and underlined. I tried the following code and it works, but doesn\'t underline.



        
相关标签:
11条回答
  • 2020-12-02 04:34

    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));
    
    0 讨论(0)
  • 2020-12-02 04:34

    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
    
    0 讨论(0)
  • 2020-12-02 04:35

    This is an easy way to add an underline, while maintaining other settings:

    textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
    
    0 讨论(0)
  • 2020-12-02 04:36

    Without quotes works for me:

    <item name="android:textStyle">bold|italic</item>
    
    0 讨论(0)
  • 2020-12-02 04:41

    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

    enter image description here

    0 讨论(0)
提交回复
热议问题