您的位置:首页 > 其它

可以响应各个方向CompoundDrawables点击操作的TextView的实现原理

2013-03-31 22:39 381 查看
TextView可以通过setCompoundDrawablesWithIntrinsicBounds在TextView内容的上下左右添加图片方便用户的需要,但默认并没有提供设置点击这些图片后响应操作的接口。本文介绍自己自定义的一个TextView达到此效果,主要功能为设置TextView各个方向图片的响应。
首先让我们看下效果



原理相对简单,利用Android View的事件响应机制,用户click屏幕某个区域会先执行onTouchEvent函数再执行onClick函数。在onTouchEvent函数中判断户点击的坐标是否在TextView相应位置CompoundDrawables可响应的范围内,若在进行标记并且在onClick函数中执行相应的响应函数即可。

主要是通过重写TextView的onTouchEvent函数和OnScrollListener的onClick函数实现

2.1 onTouchEvent函数

public boolean onTouchEvent(MotionEvent event)当用户手指接触屏幕中时,判断ACTION_DOWN点的坐标是否在四个Drawable可响应区域范围内,并保存到四个变量中,如下

mIsLeftTouched = touchLeftDrawable(event)

表示是否在左边的Drawable的可响应区域范围内,并将结果保存到mIsLeftTouched内

关于如何判断点是否在可响应区域范围见2.3响应区域判断的介绍

2.2 onClick函数

public void onClick(View v)根据onTouchEvent中判断的结果决定是否做相应的Drawable点击响应函数,如

Java代码







if (mIsLeftTouched) {
mDrawableClickListener.onClick(DrawableClickListener.DrawablePosition.LEFT);
}

if (mIsLeftTouched) {
mDrawableClickListener.onClick(DrawableClickListener.DrawablePosition.LEFT);
}

表示若在左边的Drawable的可响应区域范围内,则执行Left的onClick函数。

2.3 响应区域判断

这块涉及到一些计算以及android系统中各个View的相对坐标系

上下左右计算方法分别在touchLeftDrawable(event), touchTopDrawable(event), touchRightDrawable(event), touchBottomDrawable(event);四个函数中。

大家结合上面的四个函数和我计算时的草稿看下吧,如果对其中的计算有疑问欢迎留言交流

,下面以上边图片点击范围计算为例:

从下图可以看出上部图片的点击可响应区域即为以A、B为对角顶点的矩形,计算出A、B两点的坐标即可确定矩形。



上面是A点X和Y坐标的计算方法,下面是B点X和Y坐标的计算方法



TextView 的setCompoundDrawablesWithIntrinsicBounds与setCompoundDrawables的区别是什么?

public void setCompoundDrawables (Drawable left, Drawable top, Drawable right, Drawable bottom)

Since: API Level 1

Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use null if you do not want a Drawable there. The Drawables must already have had setBounds(Rect) called.

画的drawable的宽高是按drawable.setBound()设置的宽高,所以才有The Drawables must already have had setBounds(Rect) called.这句话之说。

-----------------------------------------------------------

public void setCompoundDrawablesWithIntrinsicBounds (Drawable left, Drawable top, Drawable right, Drawable bottom)

Since: API Level 1

Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use null if you do not want a Drawable there. The Drawables' bounds will be set to their intrinsic bounds.

而setCompoundDrawablesWithIntrinsicBounds是画的drawable的宽高是按drawable固定的宽高,即通过getIntrinsicWidth()与getIntrinsicHeight()获得,所以才有The Drawables' bounds will be set to their intrinsic bounds.这句话之说!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: