我已經創建了一個基於LinearLayout的自定義組件。這個想法是讓它成爲XML佈局的一部分,如:如何在2.2之前的Android版本中禁用佈局優化?
<com.test.MyComponent
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
/>
在運行時,該組件動態創建的內容(通過添加視圖子類的實例)。這對於Android 2.2和2.3非常適用,但在早期的平臺上,組件根本不顯示。我花了很多時間來弄清楚它爲什麼會消失,並最終找出原因。
在2.2之前的平臺上,Android進行了「巧妙」的優化。它發現XML佈局中使用的自定義類是一個LinearLayout,它沒有任何子級 - 所以它根本不打擾顯示它。
我已經嘗試了很多解決方法。這是或多或少是成功的唯一一個被添加到組件的虛擬視圖,以便它不爲空:
<com.test.MyComponent
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
>
<View
android:layout_width="1px"
android:layout_height="1px"
/>
</com.test.MyComponent>
,然後加入到組件的代碼以下重寫:
protected void dispatchDraw (Canvas canvas) {
super.dispatchDraw(canvas);
for (ChildView c : children) {
c.draw(canvas);
}
}
這允許組件及其內容出現,但存在啞視圖會破壞與組件的交互,並且任何隱藏啞元的嘗試都會導致組件消失。
看起來像有人已經付出了很大的努力來創建一個優化,現在讓我花了整整一天的時間來擺脫它。有人知道,如果有辦法禁用這種「有用的」優化?
我已經發布了冗長的回覆,但沒有出現。它還在緩和我想知道嗎? – Alexander 2011-01-25 09:39:03