Change the text color of a single ClickableSpan when pressed without affecting other ClickableSpans in the same TextView

后端 未结 8 1307
小鲜肉
小鲜肉 2020-11-29 21:19

I have a TextView with multiple ClickableSpans in it. When a ClickableSpan is pressed, I want it to change the color of its text.

I have tried setting a color state

8条回答
  •  既然无缘
    2020-11-29 22:19

    All these solutions are too much work.

    Just set android:textColorLink in your TextView to some selector. Then create a clickableSpan with no need to override updateDrawState(...). All done.

    here a quick example:

    In your strings.xml have a declared string like this:

    This is my message%1$s these words are highlighted%2$s and awesome. 
    

    then in your activity:

    private void createMySpan(){
        final String token = "#";
        String myString = getString(R.string.mystring,token,token);
    
        int start = myString.toString().indexOf(token);
        //we do -1 since we are about to remove the tokens afterwards so it shifts
        int finish = myString.toString().indexOf(token, start+1)-1;
    
        myString = myString.replaceAll(token, "");
    
        //create your spannable
        final SpannableString spannable = new SpannableString(myString);
        final ClickableSpan clickableSpan = new ClickableSpan() {
                @Override
                public void onClick(final View view) {
                    doSomethingOnClick();
                }
            };
    
        spannable.setSpan(clickableSpan, start, finish, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    
        mTextView.setMovementMethod(LinkMovementMethod.getInstance());
        mTextView.setText(spannable);
    }
    

    and heres the important parts ..declare a selector like this calling it myselector.xml:

    
    
    
        
        
    
    
    

    And last in your TextView in xml do this:

     
    

    Now you can have a pressed state on your clickableSpan.

提交回复
热议问题