Set color of TextView span in Android

前端 未结 15 1522
眼角桃花
眼角桃花 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条回答
  •  旧时难觅i
    2020-11-22 06:40

    Some answers here aren't up to date. Because, you will (in most of cases) add a custom clic action on your link.

    Besides, as provided by the documentation help, your spanned string link color will have a default one. "The default link color is the theme's accent color or android:textColorLink if this attribute is defined in the theme".

    Here is the way to do it safely.

     private class CustomClickableSpan extends ClickableSpan {
    
        private int color = -1;
    
        public CustomClickableSpan(){
            super();
            if(getContext() != null) {
                color = ContextCompat.getColor(getContext(), R.color.colorPrimaryDark);
            }
        }
    
        @Override
        public void updateDrawState(@NonNull TextPaint ds) {
            ds.setColor(color != -1 ? color : ds.linkColor);
            ds.setUnderlineText(true);
        }
    
        @Override
        public void onClick(@NonNull View widget) {
        }
    }
    

    Then to use it.

       String text = "my text with action";
        hideText= new SpannableString(text);
        hideText.setSpan(new CustomClickableSpan(){
    
            @Override
            public void onClick(@NonNull View widget) {
                // your action here !
            }
    
        }, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        yourtextview.setText(hideText);
        // don't forget this ! or this will not work !
        yourtextview.setMovementMethod(LinkMovementMethod.getInstance());
    

    Hope this will strongly help !

提交回复
热议问题