格式的TextView的样子链接 [英] Format TextView to look like link
问题描述
我一直在使用的android:自动链接
就好格式化链接等,但我需要使用安卓的onClick
,所以我不能使用,在这种情况下。其理由是,我觉得它太容易点击意外的电话号码,所以我要去拦截点击了确认对话框
,然后调用。
I've been using the android:autoLink
just fine for formatting links and such, but I need to use android:onClick
so I can't use that in this case. The reasoning is that I find it too easy to click on a phone number accidentally, so I'm going to intercept the click with a confirmation Dialog
and then call.
有没有一种简单的方法仍然使电话号码我的TextView
看起来像一个正常的可点击的链接?我捅围绕Android源$ C $ C,但找不到任何特定的风格,我参考一下。
Is there an easy way to still make the phone number in my TextView
look like a normal clickable link? I poked around the Android source code, but couldn't find any particular style for me to reference.
推荐答案
Linkify是一个伟大的阶级,它会寻找复杂的模式,如网址,电话号码等,并把他们变成URLSpans。而不是重新编写现有经常EX pressions我延长了URLSpan类,并创建升级方法的只有的电话URLSpans到自定义URLSpan一个确认对话框。
Linkify is a great class, it hunts for complex patterns like URLs, phone numbers, etc and turns them into URLSpans. Rather than re-write the existing regular expressions I extended the URLSpan class and created a method to upgrade only the telephone URLSpans to a custom URLSpan with a confirmation dialog.
首页我的扩展URLSpan类,ConfirmSpan:
First my extended URLSpan class, ConfirmSpan:
class ConfirmSpan extends URLSpan {
AlertDialog dialog;
View mView;
public ConfirmSpan(URLSpan span) {
super(span.getURL());
}
@Override
public void onClick(View widget) {
mView = widget;
if(dialog == null) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(widget.getContext());
mBuilder.setMessage("Do you want to call: " + getURL().substring(4) + "?");
mBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
openURL();
}
});
dialog = mBuilder.create();
}
dialog.show();
}
public void openURL() {
super.onClick(mView);
}
}
下一步以换出不同的跨度类方法:
Next the method to swap out the different span classes:
private void swapSpans(TextView textView) {
Spannable spannable = (Spannable) textView.getText();
URLSpan[] spans = textView.getUrls();
for(URLSpan span : spans) {
if(span.getURL().toString().startsWith("tel:")) {
spannable.setSpan(new ConfirmSpan(span), spannable.getSpanStart(span), spannable.getSpanEnd(span), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.removeSpan(span);
}
}
}
最后所有你需要做的就是创建一个自动链接属性一个TextView:
Finally all you need to do is create a TextView with the autoLink attribute:
android:autoLink="phone"
和记得调用 swapSpans()
方法。要知道,我写了这个好玩,有可能是这样做的其他方法,但我不知道他们的时刻。希望这有助于!
And remember to call the swapSpans()
method. Understand that I wrote this for fun, there may be other methods of doing this but I am unaware of them at the moment. Hope this helps!
这篇关于格式的TextView的样子链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!