可能大多数的Android开发者知道findViewById
是不是一个便宜的操作。我们大多数人知道的另一件事情是,你可以通过使用视图层次的最小的子树查找浏览用自己的ID,例如提高性能:效率findViewById
<LinearLayout
android:id="@+id/some_id_0">
<LinearLayout
android:id="@+id/some_id_1">
<LinearLayout
android:id="@+id/some_id_2">
<TextView android:id="@+id/textview" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
在这种情况下,你可能想要搜索在LinearLayout
与id == @id/textview
但什么是这样,当层级没有级联,而是分支在各个层面上,你想找到的“叶子”让我们说的意见?您是否通过寻找父母来执行findViewById
以达到分支的底部,或者您是否在更大的子集上执行findViewById
?我认为一个简单的答案将取决于案例,但也许我们可以概括一下它真正依赖于什么?
感谢
编辑:
通过一个较大的子集,我的意思是这样的:
<RelativeLayout android:id="@+id/r0">
<RelativeLayout
android:id="@+id/r1">
<LinearLayout
android:id="@+id/some_id_0">
<LinearLayout
android:id="@+id/some_id_1">
<LinearLayout
android:id="@+id/some_id_2">
<TextView android:id="@+id/textview0" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/some_id_3">
<LinearLayout
android:id="@+id/some_id_4">
<LinearLayout
android:id="@+id/some_id_5">
<TextView android:id="@+id/textview1" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="@+id/some_id_6">
<LinearLayout
android:id="@+id/some_id_7">
<LinearLayout
android:id="@+id/some_id_8">
<TextView android:id="@+id/textview2" />
<TextView android:id="@+id/textview3" />
<TextView android:id="@+id/textview4" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
所以问题是,如果我想使用findViewById
的TextView
意见LinearLayout
@+id/some_id_8
,我应该在整个容器上执行这个操作,还是我应该findViewById
LinearLayout
与@+id/some_id_8
和在这个视图findViewById
所有的TextViews
?
你能解释更多的你的2个替代品,特别是“在更大的子集上的findViewById”吗? – sotcha 2014-09-29 14:37:57
请检查我的编辑。 – overbet13 2014-09-30 09:29:11
[默认遍历](http://androidxref.com/4.4.4_r1/xref/frameworks/base/core/java/android/view/ViewGroup.java#3246)是深度优先。首先发现一个子树就像微型优化,这使代码稍微难以维护。测量以确定它是否真的有所作用 – laalto 2014-09-30 09:43:03