Android: Change the background color of a ClickableSpan when clicked

后端 未结 3 956
梦如初夏
梦如初夏 2020-12-14 08:32

I have a SpannableString with a ClickableSpan as follows

for (int i = 0; i < items.size(); i++) {
            final SpannableString span = new SpannableSt         


        
相关标签:
3条回答
  • 2020-12-14 08:45

    I extended the clickableSpan class and passed it a flag that lets me know that I should highlight it.

    SpannableStringBuilder tag;
    .... tag.setSpan(new WordSpan(i, tokens[i], wordtohighlitedID) { 
    

    .....

    import android.graphics.Color;
    import android.text.TextPaint;
    import android.text.style.ClickableSpan;
    import android.view.View;
    
    public class WordSpan extends ClickableSpan 
    {
    
        private int id;
        private TextPaint textpaint;
        public boolean shouldHilightWord = false;
        public WordSpan(int anID, String txt, int selected) {
            id =anID;
            // if the word selected is the same as the ID set the highlight flag
            if(selected == id)  {
                shouldHilightWord = true;
    
            }
    
    
        }
    
        @Override
        public void updateDrawState(TextPaint ds) {
            textpaint = ds;
            ds.setColor(ds.linkColor);
            if(shouldHilightWord){
                textpaint.bgColor = Color.GRAY;         
                textpaint.setARGB(255, 255, 255, 255);
    
            }
            //Remove default underline associated with spans
            ds.setUnderlineText(false);
    
        }
    
        public void changeSpanBgColor(View widget){
            shouldHilightWord = true;
            updateDrawState(textpaint);
            widget.invalidate();
    
    
        }
        @Override
        public void onClick(View widget) {
    
            // TODO Auto-generated method stub
    
        }
    
    
        /**
         * This function sets the span to record the word number, as the span ID
         * @param spanID
         */
        public void setSpanTextID(int spanID){
            id = spanID;
        }
    
        /**
         * Return the wordId of this span
         * @return id
         */
        public int getSpanTextID(){
            return id;
        }
    }
    
    0 讨论(0)
  • 2020-12-14 08:46

    If you're looking to get rid of the green highlight on selection, this is what you want to know:

    Apparently, overriding public void updateDrawState(TextPaint ds) in your custom class would not affect the highlight color. It is only used for setting the underline color (or hiding/showing it).

    All you need to do is: textView.setHighlightColor(Color.TRANSPARENT); where textView is what contains the ClickableSpan.

    Hope it works for all of you. Feel free to ask any related question.

    0 讨论(0)
  • 2020-12-14 09:08

    Use this:

    view.setSelector(new ColorDrawable(Color.BLUE));
    
    0 讨论(0)
提交回复
热议问题