Set color of TextView span in Android

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

    There's a factory for creating the Spannable, and avoid the cast, like this:

    Spannable span = Spannable.Factory.getInstance().newSpannable("text");
    
    0 讨论(0)
  • 2020-11-22 06:40

    Another way that could be used in some situations is to set the link color in the properties of the view that is taking the Spannable.

    If your Spannable is going to be used in a TextView, for example, you can set the link color in the XML like this:

    <TextView
        android:id="@+id/myTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColorLink="@color/your_color"
    </TextView>
    

    You can also set it in the code with:

    TextView tv = (TextView) findViewById(R.id.myTextView);
    tv.setLinkTextColor(your_color);
    
    0 讨论(0)
  • 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 !

    0 讨论(0)
提交回复
热议问题