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

后端 未结 8 1268
小鲜肉
小鲜肉 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:20

    Place the java code as below :

    package com.synamegames.orbs;
    
    import android.view.MotionEvent;
    import android.view.View;
    import android.widget.TextView;
    
    public class CustomTouchListener implements View.OnTouchListener {     
    public boolean onTouch(View view, MotionEvent motionEvent) {
    
        switch(motionEvent.getAction()){            
            case MotionEvent.ACTION_DOWN:
             ((TextView) view).setTextColor(0x4F4F4F); 
                break;          
            case MotionEvent.ACTION_CANCEL:             
            case MotionEvent.ACTION_UP:
            ((TextView) view).setTextColor(0xCDCDCD);
                break;
        } 
    
        return false;   
    } 
    }
    

    In the above code specify wat color you want .

    Change the style .xml as you want.

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    <style name="MenuFont">
        <item name="android:textSize">20sp</item>
        <item name="android:textColor">#CDCDCD</item>
        <item name="android:textStyle">normal</item>
        <item name="android:clickable">true</item>
        <item name="android:layout_weight">1</item>
        <item name="android:gravity">left|center</item>
        <item name="android:paddingLeft">35dp</item>
        <item name="android:layout_width">175dp</item> 
        <item name="android:layout_height">fill_parent</item>
    </style>
    

    Try it out and say is this you want or something else . update me dude.

    0 讨论(0)
  • 2020-11-29 22:22

    legr3c's answer helped me a lot. And I'd like to add a few remarks.

    Remark #1.

    TextView myTextView = (TextView) findViewById(R.id.my_textview);
    myTextView.setMovementMethod(new LinkTouchMovementMethod());
    myTextView.setHighlightColor(getResources().getColor(android.R.color.transparent));
    SpannableString mySpannable = new SpannableString(text);
    mySpannable.setSpan(new TouchableSpan(), 0, 7, 0);
    mySpannable.setSpan(new TouchableSpan(), 15, 18, 0);
    myTextView.setText(mySpannable, BufferType.SPANNABLE);
    

    I applied LinkTouchMovementMethod to a TextView with two spans. The spans were highlighted with blue when clicked them. myTextView.setHighlightColor(getResources().getColor(android.R.color.transparent)); fixed the bug.

    Remark #2.

    Don't forget to get colors from resources when passing normalTextColor, pressedTextColor, and pressedBackgroundColor.

    Should pass resolved color instead of resource id here

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