Set color of TextView span in Android

前端 未结 15 1675
眼角桃花
眼角桃花 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:26

    Just to add to the accepted answer, as all the answers seem to talk about android.graphics.Color only: what if the color I want is defined in res/values/colors.xml?

    For example, consider Material Design colors defined in colors.xml:

    
    
        #2196F3
    
    

    (android_material_design_colours.xml is your best friend)

    Then use ContextCompat.getColor(getContext(), R.color.md_blue_500) where you would use Color.BLUE, so that:

    wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    

    becomes:

    wordtoSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.md_blue_500)), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    

    Where I found that:

    • Working with spans in Android – Michael Spitsin – Medium

提交回复
热议问题