我正在構建遞歸層次佈局。這是我的message_with_replies.xml(我已經刪除對齊屬性和一些項目,使思想明確):如何優化遞歸嵌入式佈局?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/toggleReplies"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_expand_replies" />
<LinearLayout
android:id="@+id/replies"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
在Java代碼中,我膨脹的物品用這個佈局並將其嵌入到回覆父的佈局,然後重複這個與孩子們,讓他們形成一個樹:
root item
- child 0 of root
- - child 0 of child 0 of root
- - child 1 of child 0 of root
- - - child 0 of child 1 of child 0 of root
- child 1 of root
- child 2 of root
- child 3 of root
- - child 0 of child 3 of root
一切看起來,當我在頂層或從頂部約2-3個級別進行罰款,但隨着我走得更深,佈局響應越來越慢。減速是非線性的,並且在大約7或8的深度處,UI完全阻塞(模擬器在思考大約半分鐘後引發異常)。
很顯然,問題在於嵌入式佈局。我將線性佈局嵌入到相關佈局中,因此,根據UI佈局,我的層次結構的每個新層次都意味着兩個額外的嵌入。
如何優化?
我可以嘗試擺脫線性佈局,但我希望這不會解決問題,但只會推遲到一些更深層次,因爲我仍然會有嵌入。
當我使用其他佈局的子項目膨脹時,通常可以保持層次平坦嗎?我可以充氣物品,然後在沒有容器的情況下取出物品嗎?
加:我繞過了這個問題。現在我使用邊距構建我的樹,所以佈局沒有嵌入,並且UI不會卡住。一切看起來和工作正常。
但是原來的問題還沒有回答。
您提出的平面視圖層次*實際上是對原始問題的有效答案。你原來的問題可以解釋爲「我正在做這個非常昂貴的操作,我怎麼能優化它?」有時候,正確的答案是「減少工作量」。 Android中佈局過多的圖層總是很昂貴。 – kabuko