Android布局最佳化

來源:互聯網
上載者:User

categories: Android

在Android開發中,我們常用的布局方式主要有LinearLayout、RelativeLayout、FrameLayout等,通過這 些布局我們可以實現各種各樣的介面。與此同時,如何正確、高效的使用這些布局方式來組織UI控制項,是我們 構建優秀Android App的主要前提之一。本篇內容就主要圍繞Android布局最佳化來討論在日常開發中我們使用常 用布局需要注意的一些方面,同時介紹一款SDK內建的UI效能偵查工具HierarchyViewer。

布局原則

通過一些慣用、有效布局原則,我們可以製作出載入效率高並且複用性高的UI。簡單來說,在Android UI版面配置階段中,需要遵守的原則包括如下幾點:

盡量多使用RelativeLayout,不要使用絕對布局AbsoluteLayout;

將可複用的組件抽取出來並通過< include />標籤使用;

使用< ViewStub />標籤來載入一些不常用的布局;

使用< merge />標籤減少布局的嵌套層次;

由於Android的片段化程度很高,市面上存在的螢幕尺寸也是各式各樣,使用RelativeLayout能使我們構建 的布局適應性更強,構建出來的UI布局對多螢幕的適配效果越好,通過指定UI控制項間的相對位置,使在不同屏 幕上布局的表現能基本保持一致。當然,也不是所有情況下都得使用相對布局,根據具體情況來選擇和其他布 局方式的搭配來實現最優布局。

1、< include />的使用

在實際開發中,我們經常會遇到一些共用的UI組件,比如帶返回按鈕的導覽列,如果為每一個xml檔案都設 置這部分布局,一是重複的工作量大,二是如果有變更,那麼每一個xml檔案都得修改。還好,Android為我們 提供了< include />標籤,顧名思義,通過它,我們可以將這些共用的組件抽取出來單獨放到一個xml 檔案中,然後使用< include />標籤匯入共用布局,這樣,前面提到的兩個問題都解決了。例如上面提 到的例子,建立一個xml布局檔案作為頂部導航的共用布局。

xml common_navitationbar.xml<RelativeLayout mlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:background="@android:color/white"    android:padding="10dip" >    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:text="Back"        android:textColor="@android:color/black" />        <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:text="Title"        android:textColor="@android:color/black" /></RelativeLayout>

然後我們在需要引入導覽列的布局xml中通過< include />匯入這個共用布局。

xml main.xml<RelativeLayout mlns: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" >        <include         android:layout_alignParentTop="true"        layout="@layout/common_navitationbar" />    </RelativeLayout>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.