android textView自定义复杂显示的问题

我今天碰到一个问题,就是当字符串里出现电话时,点击电话号码要提示是否拨打电话号码,但android没有像winform一样的复杂textview,借鉴了网上的一些想法,整理如下。

TextView的字符串是“CharSequence”,我们只需要查看相应的“CharSequence”即可,

 我找到:ClickableSpan:If an object of this type is attached to the text of a TextView with a movement
method of LinkMovementMethod, the affected spans of text can be selected. If
clicked, the onClick(View)
method will be called. 

 

我们可以把电话号码变为clickableSpan,然后在onclick处理对应事件即可。

 

另:

TextView tv = new TextView(this);

tv.setText(Html.fromHtml(“<tel>15901997362</tel>”, null, new MyTagHandle()));

tv.setClickable(true);

tv.setMovementMethod(LinkMovementMethod.getInstance());//这个是必须的,否则textView的子字符串是不会响应事件的。

public final void setMovementMethod (MovementMethod
movement)

Added in API level
1

Sets the movement method (arrow key handler) to be used for this TextView.
This can be null to disallow using the arrow keys to move the cursor or scroll
the view.

Be warned that if you want a TextView with a key listener or movement method
not to be focusable, or if you want a TextView without a key listener or
movement method to be focusable, you must call setFocusable(boolean)
again after calling this to get the focusability back the way you want it.  

 

/*****

这里用来处理html容器格式的,可以不用,好处在于格式化,有利于团队合作

****/

class MyTagHandle implements TagHandler

    {

    private int startIndex=0;

    private int endIndex=0;

               /***** start:是否为容器的开始或者结束

                tag:容器

                output:输出内容

              xml:没用到****/

public void handleTag(boolean start, String tag, Editable output,

XMLReader xml) {

if(tag.toLowerCase().equals(“tel”)&&start){

this.startIndex = output.length();

}else if(tag.toLowerCase().equals(“tel”)){

this.endIndex = output.length();

output.setSpan(new MySpan(), this.startIndex, this.endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

}

}

}