gpt4 book ai didi

android - 查找特定的正则表达式单词并链接以在 android 中打开一个 Activity

转载 作者:太空狗 更新时间:2023-10-29 16:22:06 25 4
gpt4 key购买 nike

我从 API 获取文本,可以是随机的,但它包含类似于 FB 上的表达式@xyz 嗨,@abc 你好吗??1. 我需要创建一个以@开头,以空格结尾的正则表达式。2. 链接它以打开用户 Activity ,如 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..
}
});

我需要有关如何让它在我的 Activity 中创建正则表达式循环的帮助。

最佳答案

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());

关于android - 查找特定的正则表达式单词并链接以在 android 中打开一个 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11903414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com