android-textview中的多个clickspan

我有一个功能来为textview建立可点击的标签.内容如下:

    private CharSequence tagsBuilder(String text, String token) {
    SpannableStringBuilder builtTags = new SpannableStringBuilder();
    int start = 0, end = 0;

    for(int i = 0; i < 5; i++) {
        start = 0;
        end = text.indexOf(token, 0);

        try {
            if(start < end) {
                SpannableStringBuilder ssb = new SpannableStringBuilder(text.substring(start, end));
                ssb.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(View v)
                    {

                        Log.i("DEBUGTAG", "Span clicked - " + ((TextView) v).getText());
                    }
                }, start, end, 0);

                builtTags.append(ssb);
                builtTags.append(" ");
                text = text.substring(end + 1);
            }
        } catch (IndexOutOfBoundsException e) {
            break;
        }
    }

    return builtTags;
}

我可以看到带有5个单独可点击标签的textview.但是问题是,为单击的任何标签打印的日志是textview的全文.

我在这里做错什么了吗?如何获得被单击的单个标签的文本.

解决方法:

您的日志行如下:

Log.i("DEBUGTAG", "Span clicked - " + ((TextView) v).getText());

记录TextView的内容.所以…您将获得TextView的文本.如果要在其中获取令牌,则必须将其复制到其中.

您可以尝试以下方法:

private CharSequence tagsBuilder(String text, final String token) {
SpannableStringBuilder builtTags = new SpannableStringBuilder();
int start = 0, end = 0;

for(int i = 0; i < 5; i++) {
    start = 0;
    end = text.indexOf(token, 0);

    try {
        if(start < end) {
            SpannableStringBuilder ssb = new SpannableStringBuilder(text.substring(start, end));
            ssb.setSpan(new ClickableSpan() {
                private String mText = token;
                @Override
                public void onClick(View v)
                {

                    Log.i("DEBUGTAG", "Span clicked - " + mText);
                }
            }, start, end, 0);

            builtTags.append(ssb);
            builtTags.append(" ");
            text = text.substring(end + 1);
        }
    } catch (IndexOutOfBoundsException e) {
        break;
    }
}

return builtTags;
}
上一篇:java-如何获取Android EditText组件的值作为整数?


下一篇:设置为Android 4.0时,Eclipse无法识别numberPassword吗?