我正在使用Linkify
来检测TextView
中的主题标签并且它工作正常,但我想在EditText
控件内实现它。
这是我在Linkify
中使用TextView
的方式:
Pattern tagMatcher = Pattern.compile(("#([ء-يA-Za-z0-9_-]+)"));
String newActivityURL = "content://com.hashtag.jojo/";
Pattern urlPattern = Patterns.WEB_URL;
TransformFilter transformFilter = new TransformFilter() {
// skip the first character to filter out '@'
public String transformUrl(final Matcher match, String url) {
return match.group(0);
}
};
Linkify.addLinks(TextView, Linkify.ALL);
Linkify.addLinks(TextView, tagMatcher,newActivityURL, null,transformFilter);
如何将此应用于EditText
?
答案 0 :(得分:2)
使用EditText而不是TextView执行操作,因为EditText从TextView扩展。它必须工作正常。
小例子:
EditText editText1 = (EditText) findViewById(R.id.editText1);
editText1.setText("http://http://www.dzone.com/");
Linkify.addLinks(editText1 , Linkify.WEB_URLS);
如果你想实时检查它,就这样做:
editText1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Linkify.addLinks(editText1 , Linkify.WEB_URLS);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
<强>更新强>
final TransformFilter filter = new TransformFilter() {
public final String transformUrl(final Matcher match, String url) {
return match.group();
}
};
final Pattern hashtagPattern = Pattern.compile("#([ء-يA-Za-z0-9_-]+)");
final String hashtagScheme = "content://com.hashtag.jojo/";
final Pattern urlPattern = Patterns.WEB_URL;
editText1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
System.out.println(count);
}
@Override
public void afterTextChanged(Editable s) {
Linkify.addLinks(s, hashtagPattern, hashtagScheme, null, filter);
Linkify.addLinks(s, urlPattern, null, null, filter);
}
});