Android - set TextView TextStyle programmatically?

前端 未结 11 571
南旧
南旧 2020-12-02 05:04

Is there a way to set the textStyle attribute of a TextView programmatically? There doesn\'t appear to be a setTextStyle() method.

相关标签:
11条回答
  • 2020-12-02 05:50

    This worked for me

    textview.setTypeface(textview.getTypeface(), Typeface.BOLD);
    

    or

    textview.setTypeface(Typeface.DEFAULT_BOLD);
    
    0 讨论(0)
  • 2020-12-02 05:53

    So many way to achieve this task some are below:-

    1.

    String text_view_str = "<b>Bolded text</b>, <i>italic text</i>, even <u>underlined</u>!";
    TextView tv = (TextView)findViewById(R.id.ur_text_view_id);
    tv.setText(Html.fromHtml(text_view_str));
    

    2.

    tv.setTypeface(null, Typeface.BOLD);
    tv.setTypeface(null, Typeface.ITALIC);
    tv.setTypeface(null, Typeface.BOLD_ITALIC);
    tv.setTypeface(null, Typeface.NORMAL);
    

    3.

    SpannableString spannablecontent=new SpannableString(o.content.toString());
    spannablecontent.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 
                             0,spannablecontent.length(), 0);
    // set Text here
    tt.setText(spannablecontent);
    

    4.

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
        <style name="boldText">
            <item name="android:textStyle">bold|italic</item>
            <item name="android:textColor">#FFFFFF</item>
        </style>
    
        <style name="normalText">
            <item name="android:textStyle">normal</item>
            <item name="android:textColor">#C0C0C0</item>
        </style>
    
    </resources>
    
     tv.setTextAppearance(getApplicationContext(), R.style.boldText);
    

    or if u want through xml

    android:textStyle="normal"
    android:textStyle="normal|bold"
    android:textStyle="normal|italic"
    android:textStyle="bold"
    android:textStyle="bold|italic"
    
    0 讨论(0)
  • 2020-12-02 05:56
    textview.setTypeface(Typeface.DEFAULT_BOLD);
    

    setTypeface is the Attribute textStyle.

    As Shankar V added, to preserve the previously set typeface attributes you can use:

    textview.setTypeface(textview.getTypeface(), Typeface.BOLD);
    
    0 讨论(0)
  • 2020-12-02 05:56

    As mentioned here, this feature is not currently supported.

    0 讨论(0)
  • 2020-12-02 06:02

    Search for setTextAppearance or also setTextTypeface. There is similar question on stackoverflow: How to change a TextView's style at runtime

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