我试图在我的TextView中识别主题标签,并使其可点击,以便我们可以在用户点击Hashtag时将用户带到另一个视图.
我设法使用模式匹配在TextView中识别Hashtags,并在运行时显示为彩色.但是,我需要使Hashtag可点击.
这是我的代码:
SpannableString hashText = new SpannableString("I just watched #StarWars and it was incredible. It's a #MustWatch #StarWars"); Matcher matcher = Pattern.compile("#([A-Za-z0-9_-]+)").matcher(hashText); while (matcher.find()) { hashText.setSpan(new ForegroundColorSpan(Color.parseColor("#000763")),matcher.start(),matcher.end(),0); String tag = matcher.group(0); } holder.caption.setText(hashText); //I need to set an OnClick listener to all the Hashtags recognised
解决方法
有一种方式…看到你的问题后,我只是谷歌…我发现这个,我希望它会工作…
1.
你可以使用android.text.style.ClickableSpan link
SpannableString ss = new SpannableString("Hello World"); ClickableSpan span1 = new ClickableSpan() { @Override public void onClick(View textView) { // do some thing } }; ClickableSpan span2 = new ClickableSpan() { @Override public void onClick(View textView) { // do another thing } }; ss.setSpan(span1,4,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); ss.setSpan(span2,6,10,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(ss); textView.setMovementMethod(LinkMovementMethod.getInstance());
另一种方式.. link
TextView myTextView = new TextView(this); String myString = "Some text [clickable]"; int i1 = myString.indexOf("["); int i2 = myString.indexOf("]"); myTextView.setMovementMethod(LinkMovementMethod.getInstance()); myTextView.setText(myString,BufferType.SPANNABLE); Spannable mySpannable = (Spannable)myTextView.getText(); ClickableSpan myClickableSpan = new ClickableSpan() { @Override public void onClick(View widget) { /* do something */ } }; mySpannable.setSpan(myClickableSpan,i1,i2 + 1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
答案刚刚从这些链接复制…