有一句古話:不論黑貓白貓,能抓到耗子就是好貓。這個也許在某些方面是有道理的,但對於我們追求精益求精的思想是背道而馳的,往往就是因爲滿足於一個結果,而放棄探求更加優化的處理方法。
當關注應用程序或者遊戲所達到的結果時,往往非常容易忽視一些優化的問題,例如內存優化,線程優化,Media優化和UI優化等等。不同的模塊都存在更爲巧妙的方式來對待一般性問題,所以每當我們實現一個行爲後,稍微多花一些時間來考慮目前所作的工作是否存在更爲高效的解決辦法。
這一次我們對常用的UI Layout優化說起,這個例子轉載於
android developing blog
在Android中最常用LinearLayout表示UI的框架,而且也是最直觀和方便的方法。例如創建一個UI用於展現Item的基本內容。如圖所示:
線框圖:
直接可以通過LinearLayout快速的實現這個UI的排列:
<LinearLayout xmlns: android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="?android:attr/listPreferredItemHeight" android:padding="6dip"> <ImageView android:id="@+id/icon" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginRight="6dip" android:src="@drawable/icon" /> <LinearLayout android:orientation="vertical" android:layout_width="0dip" android:layout_weight="1" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1" android:gravity="center_vertical" android:text="My Application" /> <TextView android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1" android:singleLine="true" android:ellipsize="marquee" android:text="Simple application that shows how to use RelativeLayout" /> </LinearLayout> </LinearLayout> |
儘管可以通過Linearlayout實現我們所預想的結果,但是在這裏存在一個優化的問題,尤其是針對爲大量Items。比較RelativeLayout和LinearLayout,在資源利用上前者會佔用更少的資源而達到相同的效果,以下是用RelativeLayout實現的代碼:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="?android:attr/listPreferredItemHeight" android:padding="6dip"> <ImageView android:id="@+id/icon" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignParentTop="true" android:layout_alignParentBottom="true" android:layout_marginRight="6dip" android:src="@drawable/icon" /> <TextView android:id="@+id/secondLine" android:layout_width="fill_parent" android:layout_height="26dip" android:layout_toRightOf="@id/icon" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:singleLine="true" android:ellipsize="marquee" android:text="Simple application that shows how to use RelativeLayout" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_toRightOf="@id/icon" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_above="@id/secondLine" android:layout_alignWithParentIfMissing="true" android:gravity="center_vertical" android:text="My Application" /> </RelativeLayout> |
針對RelativeLayout有一點需要注意,因爲它內部是通過多個View之間的關係而確定的框架,那麼當其中某一個View因爲某些需要調用GONE來完全隱藏掉後,會影響與其相關聯的Views。Android爲我們提供了一個屬性 alignWithParentIfMissing 用於解決類似問題,當某一個View無法找到與其相關聯的Views後將依據alignWithParentIfMissing的設定判斷是否與父級View對齊。
下邊是兩種不同layout在Hierarchy Viewer中的層級關係圖: