行。这些是我的问题。
- 我需要使用正则表达式来归档除字母之外的所有内容,然后我需要将找到的单词包含在 $word 标记中。有了这个 str = str.replaceAll(pattern, "$0");。现在我正在过滤所有正确的元素(标点符号、数字等),但它将每个单词中的每个字母都包含在 a 标签中,而不是单词中。那么如何使用正则表达式将字母组合成一个单词呢?
from "(a tag open)t(a close)(a tag open)h(a close)(a tag open)i(a close)(a tag open)s(a close) (a tag open)i(a close)(a tag open)s(a close) (a tag open)w(a close)(a tag open)r(a close)(a tag open)o(a close)(a tag open)n(a关闭)(标签打开)g(关闭)“;
到 :
"(a tag open)this(a close) (a tag open) is(a close) (a tag open)right(a close)";
然后我让它们可点击,我需要捕捉点击事件并在点击的单词上获取屏幕上的位置,因为我想使用点击的事件使工具提示显示在点击的单词下方。感谢您的帮助。
公共类 MainActivity 扩展 Activity {
public String text = "This is just a sentence to test you. 23 this is another number23!g?";
public TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = explode(text);
tv = (TextView) findViewById(R.id.tv1);
tv.setLinksClickable(true);
tv.setMovementMethod(LinkMovementMethod.getInstance());
Spanned article = Html.fromHtml(text, null, null);
setHTML(article);
}
public void setHTML(Spanned html) {
SpannableString message = new SpannableString(html.toString());
Object[] spans = html.getSpans(0, html.length(), Object.class);
for (Object span : spans) {
int start = html.getSpanStart(span);
int end = html.getSpanEnd(span);
int flags = html.getSpanFlags(span);
if (span instanceof URLSpan) {
URLSpan urlSpan = (URLSpan) span;
span = new CallbackSpan(urlSpan.getURL());
}
message.setSpan(span, start, end, flags);
}
tv.setText(message);
}
public String explode(String str){
String pattern = "([a-zA-Z])";
str = str.replaceAll(pattern, "<a href=\"$0\">$0</a>");
return str;
}
private final class CallbackSpan extends ClickableSpan {
private String m_data;
private String url_main;
public CallbackSpan(String url) {
m_data = url.substring(0);
url_main = url;
}
public void onClick(View view) {
TextView item = (TextView)findViewById(R.id.tv2);
item.setText(url_main + " was clicked.");
Log.d("item", url_main);
}
}
}