offsetDescendantRectToMyCoords和offsetRectIntoDescendantCoords源码剖析

本文深入解析了日常工作中常用的两种坐标系转换方法,通过分析源码揭示了这两种方法背后的实现原理。一种方法是从子View坐标系转换到父View坐标系,另一种则是相反方向的转换。

日常工作中经常需要对坐标系作转换,那么我们应该对这2个方法不会感到陌生。

首先我们可以看一下这2个方法的源码。可以看到都调用了同一个offsetRectBetweenParentAndChild方法。

然后我们看一下offsetRectBetweenParentAndChild方法。5916行是一个while循环,主要起到一个从子View一直回溯到this的作用。根据源码可以发现,方法一其实就是提供一个位于descendant坐标系的rect,然后转移到this坐标系。方法二就是提供一个位于this坐标系的rect,然后转移到descendant坐标系。

Caused by: java.lang.IllegalArgumentException: parameter must be a descendant of this view at android.view.ViewGroup.offsetRectBetweenParentAndChild(ViewGroup.java:6295) at android.view.ViewGroup.offsetDescendantRectToMyCoords(ViewGroup.java:6224) at com.st.launcher.view.TVRecyclerView.findFocusView(TVRecyclerView.java:632) at com.st.launcher.view.TVRecyclerViewTest.testFindFocusView_1_withRealViews(TVRecyclerViewTest.java:824) @Test public void testFindFocusView_1_withRealViews() throws Exception { TVRecyclerView spy = spy(new TVRecyclerView(RuntimeEnvironment.application)); FrameLayout parent = new FrameLayout(RuntimeEnvironment.application); Button child = new Button(RuntimeEnvironment.application); parent.addView(child); child.setFocusable(true); child.setFocusableInTouchMode(true); Method findFocusView = TVRecyclerView.class.getDeclaredMethod("findFocusView", View.class, View.class); findFocusView.setAccessible(true); findFocusView.invoke(spy, parent, child); } private void findFocusView(View parent, View child) { if (child.isFocusable() && child.isFocusableInTouchMode()) { Rect rect = new Rect(); child.getDrawingRect(rect); offsetDescendantRectToMyCoords(child, rect); offsetRectIntoDescendantCoords(parent, rect); Log.d(TAG, "onChildAttachedToWindow: rect = " + rect); if (rect.contains(mFocusRect)) { if (nofityFocusView != null) { nofityFocusView.clear(); nofityFocusView = null; } nofityFocusView = new WeakReference<View>(child); } } else if (child instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) child; int count = viewGroup.getChildCount(); for (int i = 0; i < count; i++) { findFocusView(parent, viewGroup.getChildAt(i)); } } }
08-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值