2

我从 API 获取文本,可以是随机的,但它包含像 FB @xyz hi, @abc 你怎么样?1.我需要创建一个以@开头,以空格结尾的正则表达式。2. 链接它以打开用户活动,如 XYZ 或 ABC。请帮助我,我试图创建一个类,

import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.TextView;

public class ClickSpan extends ClickableSpan {

    private OnClickListener mListener;

    public ClickSpan(OnClickListener listener) {
        mListener = listener;
    }

    @Override
    public void onClick(View widget) {
        if (mListener != null) mListener.onClick();
    }

    public interface OnClickListener {
        void onClick();
    }


    /**
     * To clickify a textview
     * @param view
     * @param clickableText
     * @param listener
     */
    public static void clickify(TextView view, final String clickableText, 
            final ClickSpan.OnClickListener listener) {

        CharSequence text = view.getText();
        String string = text.toString();
        ClickSpan span = new ClickSpan(listener);

        int start = string.indexOf(clickableText);
        int end = start + clickableText.length();
        if (start == -1) return;

        if (text instanceof Spannable) {
            ((Spannable)text).setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            SpannableString s = SpannableString.valueOf(text);
            s.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            view.setText(s);
        }

        MovementMethod m = view.getMovementMethod();
        if ((m == null) || !(m instanceof LinkMovementMethod)) {
            view.setMovementMethod(LinkMovementMethod.getInstance());
        }
    }

} 

像这样打电话,

clickify(textView, clickText,new ClickSpan.OnClickListener()
     {
        @Override
        public void onClick() {
           startActivity here..
        }
    });

我需要关于如何让它在我的活动中工作的帮助,以创建一个正则表达式循环。

4

1 回答 1

6
public class ClickableURLSpan extends URLSpan {
    public ClickableURLSpan(String url) {
        super(url);
    }

    @Override
    public void onClick(View widget) {
        String clickedText = getURL();

            // START your activity here
    }
}

现在您可以链接您的文本:

CharSequence input = "@xyz hi, @abc how u??!";
SpannableStringBuilder builder = new SpannableStringBuilder(input);

Pattern pattern = Pattern.compile("@.*?\\s");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
    int start = matcher.start();
    int end = matcher.end();

    String text = input.subSequence(start, end).toString();

    ClickableURLSpan url = new ClickableURLSpan(text);
    builder.setSpan(url, start, end, 0);
}

textView.setText(builder);
textView.setMovementMethod(LinkMovementMethod.getInstance());
于 2012-08-10T15:00:17.043 回答