可能大多數的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