Set color of TextView span in Android

前端 未结 15 1685
眼角桃花
眼角桃花 2020-11-22 05:54

Is it possible to set the color of just span of text in a TextView?

I would like to do something similar to the Twitter app, in which a part of the text is blue. See

15条回答
  •  一个人的身影
    2020-11-22 06:15

    Below works perfectly for me

        tvPrivacyPolicy = (TextView) findViewById(R.id.tvPrivacyPolicy);
        String originalText = (String)tvPrivacyPolicy.getText();
        int startPosition = 15;
        int endPosition = 31;
    
        SpannableString spannableStr = new SpannableString(originalText);
        UnderlineSpan underlineSpan = new UnderlineSpan();
        spannableStr.setSpan(underlineSpan, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    
        ForegroundColorSpan backgroundColorSpan = new ForegroundColorSpan(Color.BLUE);
        spannableStr.setSpan(backgroundColorSpan, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    
        StyleSpan styleSpanItalic  = new StyleSpan(Typeface.BOLD);
    
        spannableStr.setSpan(styleSpanItalic, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    
        tvPrivacyPolicy.setText(spannableStr);
    

    Output for above code

提交回复
热议问题