編輯:Android 開發實例
今天來談談如何善用 Android 提供的工具來優化我們的版面配置。首先,我們寫一個最簡單的框架配置,用來實現層疊效果:
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="300dip" android:layout_height="300dip" android:background="#00008B" android:layout_gravity="center" /> <TextView android:layout_width="250dip" android:layout_height="250dip" android:background="#0000CD" android:layout_gravity="center" /> <TextView android:layout_width="200dip" android:layout_height="200dip" android:background="#0000FF" android:layout_gravity="center" /> <TextView android:layout_width="150dip" android:layout_height="150dip" android:background="#00BFFF" android:layout_gravity="center" /> <TextView android:layout_width="100dip" android:layout_height="100dip" android:background="#00CED1" android:layout_gravity="center" /> </FrameLayout>
Hierarchy Viewer 位於 SDK 的 tools 目錄下,是一個相當實用的版面配置優化工具,同時也能透過它學習他人的配置巧思。打開後,介面簡潔地列出當前裝置上的所有程序,位於前景的程序以粗體顯示。上方有三個選項,分別是重新整理程序清單、將層次結構載入樹狀圖,以及擷取螢幕到帶有像素網格的放大鏡中。
在模擬器上開啟配置,點選 Load View 後進入分析介面。左側的大圖為應用配置的樹狀結構,標示了元件名稱與 id 等資訊;每個節點下方的圓形代表該節點的渲染速度,由左至右分別為測量大小、配置與繪製,綠色最快、紅色最慢。點擊可查看該元件的預覽圖、子節點數量與具體渲染時間,右側則顯示預覽、元件屬性與介面結構。
點擊左下角的第三個圖示可切換到像素視圖。此時能精準定位元件的座標與顏色,讓配置觀察更為直觀方便。
layoutopt 是 Android 提供的版面配置分析工具,能分析指定配置並提出優化建議。執行時,開啟命令列進入 SDK 的 tools 目錄,輸入 layoutopt 加上配置目錄路徑即可。工具會列出分析後的建議,例如建議替換標籤等。
以下是一些常見的輸出訊息:
$ layoutopt samples/ samples/compound.xml 7:23 The root-level <FrameLayout/> can be replaced with <merge/> 11:21 This LinearLayout layout or its FrameLayout parent is useless samples/simple.xml 提示未使用到該配置 7:7 The root-level <FrameLayout/> can be replaced with <merge/> samples/too_deep.xml -1:-1 This layout has too many nested layouts: 13 levels, it should have <= 10! 20:81 This LinearLayout layout or its LinearLayout parent is useless samples/too_many.xml 7:413 The root-level <FrameLayout/> can be replaced with <merge/> -1:-1 This layout has too many views: 81 views, it should have <= 80!
透過這套工具,我們便能很有針對性地優化 UI 設計與配置結構。以上就是今天的分享。
Android 資料備份:用 Backup Agent 把 App 資料存到雲端
Android 提供備份服務,讓你把應用程式的資料與設定備份到遠端「雲端」儲存空間,日後重灌或換機時就能還原到備份當下的狀態。要特別注意的是,這個機制只涵蓋 App 自身
Android 手機衛士(一):實作 Splash 啟動畫面
什麼是 Splash? Splash 是應用程式啟動時先出現的簡短畫面,通常用來展示品牌 LOGO、應用名稱、版本資訊或初始化狀態。手機遊戲與第三方 App 常見這種設計
Android AlertDialog 教學:用正負按鈕分流頁面跳轉
當程式需要使用者先確認「是」或「否」,又不想切換畫面時,警告對話框(Alert Dialog)是最合適的選擇。它會疊在目前 Activity 之上,等待使用者做出決定後再
Android 加載 Spinner:用 ProgressBar 顯示不確定進度
在 Android 中,可以透過加載進度條來顯示任務的進展。進度條有兩種形狀:加載欄與加載微調(spinner)。本章我們將討論 spinner。 Spinner 用於顯