本文介绍了安卓:点击后更改ClickableSpan的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ClickableSpan一个SpannableString如下:

I have a SpannableString with a ClickableSpan as follows

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

            span.setSpan(new ClickableSpan() {

                @Override
                public void onClick(View widget) {

                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    ds.setColor(Color.LTGRAY);
                    ds.setUnderlineText(false);

                }
            }, 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            builder.append(span);
        }

//my text view
txt.setText(builder);
txt.setMovementMethod(LinkMovementMethod.getInstance());

我想要做的是改变跨度的前景色点击时。

what I want to do is to change the foreground color of the span when clicked.

我怎么能做到这一点?

推荐答案

我延长了clickableSpan类,并通过它一个标志,让我知道,我应该强调它。

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;
    }
}

这篇关于安卓:点击后更改ClickableSpan的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-04 12:25