为什么 Android 视图 class 有 'outValues style' 少数属性的吸气剂?

Why Android View class has 'outValues style' getters for handful of properties?

您可以使用标准 [=heightalphaidmatrixdrawingTimeelevation 等视图属性=47=]s(如 getHeight()getAlpha()getId()...)。

但是,您有一些视图的属性(其中大多数具有 PointRect return 类型),例如 locationInWindowglobalVisibleRect , locationInScreen, drawingRect, drawingCache 隐藏在 getter 之下,迫使您预先使用空构造函数创建 returning 对象,并将这些对象作为getter 参数,以便数据被 'saved' 提供给他们。

globalVisibleRect 的 getter 示例:

public final boolean getGlobalVisibleRect(Rect r)

强迫你做这样的事情 (Kotlin):

val rect = Rect()
getGlobalVisibleRect(rect)
doSomeStuffWithRect(rect)

它不是很一致,也不能使用 Android Studio 中的“表达式”选项卡进行实时调试,而且确实很麻烦。

为什么要这样做?如果视图不可见,我看到一些方法 returning false 布尔值,因此你知道 returned 数据无效,但不应该用 returning 解决null 值,如果方法已经知道它产生了不可用的信息?另一方面,getLocationOnScreen return 是无效的,没有额外的参数,所以我真的不明白你为什么要那样复杂化。

Why is it done that way?

鼓励对象的重用,例如通过对象池。创建无数 Rect 个实例并让 GC 清理它们是低效的,尤其是在 2006 年时代的设备上。创建和收集不计其数的 Rect 实例也会使堆碎片化,这对于 Android 8.0 之前的设备来说仍然是一个问题,尽管 Android 5.0 的变化有所帮助。