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

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.
学弟,学长只能帮到你这里了!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值