Android佈局優化經驗總結

佈局優化的目的是爲了製作出高效、可複用的UI。 本文主要是對博主在平時開發的過程中關於佈局經驗的一個總結,覺得還有些用處,記錄下來分享給大家。


HierarchyViewer

HierarchyViewer用來查看佈局的層次,可以在sdk/tools下面找到,也可以通過Android Device Moniter打開。在部分手機上因爲系統版本沒有開放查看佈局的權限,所以HierarchyViewer可能無法正常使用,可以使用ViewServer來運行HierarchyViewer。

<include>

這裏的<include>標籤與jsp中的<include>類似,都是爲了包含可以重複使用的佈局。把常用的佈局提取出來做成單獨的xml文件,在需要的時候直接<include>,提高開發效率。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    <strong><include layout="@layout/header"/></strong>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="StaticBroadcast"
        android:id="@+id/btn_static"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

這裏的header就是我們已經開發好的通用頂欄佈局。

<merge>

<merge>主要是用來減少UI的層級,提高加載速度。<merge>常用來代替FrameLayout或者當一個佈局include另一個佈局的時候,<merge>用來消除目錄結構中的多餘ViewGroup。當你在一個FrameLayout中include一個layout時
<FrameLayout>
   <include layout="@layout/layout2"/>
</FrameLayout>

layout2.xml
<FrameLayout>
   <TextView />
</FrameLayout>

這樣整個Layout就變成了
<FrameLayout>
   <FrameLayout>
      <TextView />
   </FrameLayout>
</FrameLayout>

這顯然不是我們想要的,把layout2.xml改成
<merge>
   <TextView />
</merge>

整個Layout變成
<FrameLayout>
   <TextView />
</FrameLayout

<ViewStub>

<ViewStub>與<include>類似,也是加在另外一個佈局,但是與include不同的是,<ViewStub>引入的佈局默認是不顯示的,不會佔用CPU和內存,所以經常用來引入那些默認不顯示的佈局,比如進度條、錯誤提示等。

新建一個error.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

   <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Message" />

</RelativeLayout>

使用ViewStub

<RelativeLayout>xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    ...

    <ViewStub
        android:id="@+id/error_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout="@layout/error" />

</RelativeLayout>

在代碼中顯示ViewStub可以使用

((ViewStub) findViewById(R.id.error_layout)).setVisibility(View.VISIBLE);  或者View importPanel = ((ViewStub) findViewById(R.id.error_layout)).inflate();  


發佈了58 篇原創文章 · 獲贊 26 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章