Is it possible to have multiple styles inside a TextView?

后端 未结 18 1853
醉梦人生
醉梦人生 2020-11-21 17:34

Is it possible to set multiple styles for different pieces of text inside a TextView?

For instance, I am setting the text as follows:

tv.setText(line         


        
18条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 17:57

    If you want to be able to add the styled text in xml you can create a custom view extending TextView and override setText():

    public class HTMLStyledTextView extends TextView
    {
        public HTMLStyledTextView(Context context) {
            super(context);
        }
    
        public HTMLStyledTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public HTMLStyledTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        @Override
        public void setText(CharSequence text, BufferType type)
        {
           super.setText(Html.fromHtml(text.toString()), type);
        }
    }
    

    Then, you can use it like this (replace PACKAGE_NAME with your package name):

    
    

提交回复
热议问题