我实际上并没有尝试启动 URL 链接
由于您不需要使用 URL,因此不必费心尝试创建自定义 Linkify 方案,因为它只创建 URLSpans。您只想从 TextView 中的关键字启动 Activity。正如我在您的一个类似但不重复的问题中所述,我将使用自定义跨度,引入 ActivitySpan:
public class ActivitySpan extends ClickableSpan {
String keyword;
public ActivitySpan(String keyword) {
super();
this.keyword = keyword;
}
@Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, AnotherActivity.class);
intent.putExtra("keyword", keyword);
context.startActivity(intent);
}
}
这里没有花里胡哨的东西,这个跨度需要[keyword]
你用括号括起来并将它传递给另一个活动。
虽然由于 URLSpan 我不喜欢使用 Linkify 的想法,但它的模式匹配和跨度创建很棒,所以我复制并修改了它:
private void addLinks(TextView textView, Pattern pattern) {
SpannableString spannable = SpannableString.valueOf(textView.getText());
Matcher matcher = pattern.matcher(spannable);
// Create ActivitySpans for each match
while (matcher.find())
spannable.setSpan(new ActivitySpan(matcher.group()), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Set new spans in TextView
textView.setText(spannable);
// Listen for spannable clicks, if not already
MovementMethod m = textView.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
if (textView.getLinksClickable()) {
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
请注意,此方法不会删除[brackets]
每个关键字周围的内容,但您可以在 while 循环中轻松执行此操作。
要使用它,只需将 TextView 和 Pattern 传递给addLinks()
inonCreate()
和瞧!
适合您的工作示例:
public class Example extends Activity {
Pattern pattern = Pattern.compile("\\[[^]]*]");
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
popupDefinition("Example: A [pattern] or [model], as of something to be [imitated] or [avoided]");
}
// It seems like you can call "popupDefinition(dictionaryMap.get(term));" rather than pass both.
public void popupDefinition(String string){
SpannableString spannable = new SpannableString(string);
Matcher matcher = pattern.matcher(spannable);
// Create ActivitySpans for each match
while (matcher.find())
spannable.setSpan(new ActivitySpan(matcher.group()), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Create a new TextView with these spans and enable the clickable links
TextView textView = new TextView(this);
textView.setText(spannable);
textView.setMovementMethod(LinkMovementMethod.getInstance());
// Create and display an AlertDialog with this TextView
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setView(textView)
.create();
alertDialog.show();
}
public class ActivitySpan extends ClickableSpan {
String keyword;
public ActivitySpan(String keyword) {
super();
this.keyword = keyword;
}
@Override
public void onClick(View v) {
Context context = v.getContext();
Toast.makeText(context, keyword, Toast.LENGTH_SHORT).show();
}
}
}