android 关于如何获取控件矩阵 getHitRect

来源:互联网 发布:软件著作权加急 编辑:程序博客网 时间:2024/05/19 23:25

getHitRect作为获取控件所在的矩阵范围函数,简直就像个神器。当然他也有不给力的情况,我们平常调用时候如果是在控件的监听器里调用就没事,但是如果主动的在onCreate 或者 onResume中,拿到的矩阵坐标全是0.

解决如下:

As the hit rect is in the parent coordinate space, the parent first needs to layout its children which it hasn't done yet during onCreate(). Take a look at the solution here for an example of running in post(). If you have a custom view, getHitRect() within onDraw() will give you the correct dimensions too.

大概意思就是getHitRect方法不能直接在onCreate中调用 ,原因是该控件还未在这个界面框架中得以测量布局,不知道到底是多少,所以我们要寻找一个时机去做这件事,两个方法:

方法1   运用该控件执行post    (就把下面的那个parent当成你要获取getHitRect的方法)

I asked a friend at Google and they were able to help me figure out how to use TouchDelegate. Here's what we came up with:

final View parent = (View) delegate.getParent();parent.post( new Runnable() {    // Post in the parent's message queue to make sure the parent    // lays out its children before we call getHitRect()    public void run() {        final Rect r = new Rect();        delegate.getHitRect(r);        r.top -= 4;        r.bottom += 4;        parent.setTouchDelegate( new TouchDelegate( r , delegate));    }});
方法2  自定义该控件 覆写onDraw  调用getHitRect.
学弟,学长只能帮到你这里了!
原创粉丝点击