Is it possible to have multiple styles inside a TextView?

后端 未结 18 1854
醉梦人生
醉梦人生 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 18:13

    I was running into the same problem. I could use fromHtml, but I am android now, not web, so I decided to try this out. I do have to localize this though so I gave it a shot using string replacement concept. I set the style on the TextView to be the main style, then just format the other peices.

    I hope this helps others looking to do the same thing - I don't know why this isn't easier in the framework.

    My strings look like this:

    
    {0} You will need a {1} to complete this assembly
    1:
    screwdriver, hammer, and measuring tape
    

    Here are the styles:

    
    
    
    
    

    Here is my code that calls my formatStyles method:

    
    SpannableString formattedSpan = formatStyles(getString(R.string.my_text), getString(R.string.text_sub0), R.style.style0, getString(R.string.main_text_sub1), R.style.style1);
    textView.setText(formattedSpan, TextView.BufferType.SPANNABLE);
    

    The format method:

    
    private SpannableString formatStyles(String value, String sub0, int style0, String sub1, int style1)
    {
        String tag0 = "{0}";
        int startLocation0 = value.indexOf(tag0);
        value = value.replace(tag0, sub0);
    
        String tag1 = "{1}";
        int startLocation1 = value.indexOf(tag1);
        if (sub1 != null && !sub1.equals(""))
        {
            value = value.replace(tag1, sub1);
        }
    
        SpannableString styledText = new SpannableString(value);
        styledText.setSpan(new TextAppearanceSpan(getActivity(), style0), startLocation0, startLocation0 + sub0.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (sub1 != null && !sub1.equals(""))
        {
            styledText.setSpan(new TextAppearanceSpan(getActivity(), style1), startLocation1, startLocation1 + sub1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    
        return styledText;
    }
    

提交回复
热议问题