您的位置:首页 > 移动开发 > Android开发

android实现clickspan点击的效果(类似@好友,当action_up时,效果消失)

2013-12-10 22:32 417 查看
要实现如下效果:

之前:



action_down:



松开之后,又回到第一个图片状态:

主要是实现LinkMovementMethod继承类,然后重写ontouchevent就ok了

public boolean onTouchEvent(TextView widget, Spannable buffer,
			MotionEvent event) {
		// TODO Auto-generated method stub
		 int action = event.getAction();

	        if (action == MotionEvent.ACTION_UP ||
	            action == MotionEvent.ACTION_DOWN) {
	            int x = (int) event.getX();
	            int y = (int) event.getY();

	            x -= widget.getTotalPaddingLeft();
	            y -= widget.getTotalPaddingTop();

	            x += widget.getScrollX();
	            y += widget.getScrollY();

	            Layout layout = widget.getLayout();
	            int line = layout.getLineForVertical(y);
	            int off = layout.getOffsetForHorizontal(line, x);

	            ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);

	            if (link.length != 0) {
	                if (action == MotionEvent.ACTION_UP) {
	                    link[0].onClick(widget);
	                    buffer.setSpan(new BackgroundColorSpan(Color.TRANSPARENT), 
	                			buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0]),
	                			Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
	                } else if (action == MotionEvent.ACTION_DOWN) {
	                	buffer.setSpan(new BackgroundColorSpan(Color.GRAY), 
	                			buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0]),
	                			Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
	                    Selection.setSelection(buffer,
	                                           buffer.getSpanStart(link[0]),
	                                           buffer.getSpanEnd(link[0]));
	                }

	                return true;
	            } else {
	                Selection.removeSelection(buffer);
	            }
	        }

	        return Touch.onTouchEvent(widget, buffer, event);
	}
clickspan中的onclick:

@Override
	    public void onClick(View widget) {
//	    	((TextView)widget).setTextColor(Color.RED);
	    	Spannable spannable = ((Spannable)((TextView)widget).getText());
	    	Selection.removeSelection(spannable);
//              Selection.setSelection(spannable, 0);
	    	Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
	    }


主要是上面的两个点

参见:/article/3564350.html

http://stackoverflow.com/questions/16792963/android-clickablespan-intercepts-the-click-event

http://gundumw100.iteye.com/blog/851009

demo链接:http://download.csdn.net/detail/swust_chenpeng/6694065
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: