Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Studio 技巧:布局預覽時填充測試數據

編輯:關於 Android 程式設計

Android Studio 的布局預覽功能非常好用,調 UI 時我們往往需要實時預覽來確認效果。切換到 Design 視圖就能看到界面,而如果能在布局上填充一些測試數據,預覽效果會更真實——比如在 TextView 裡設定 text 屬性來檢查字體大小與布局是否正確。但問題是,正式環境中我們又不想保留這些額外數據。這篇要介紹的技巧正好能解決這個矛盾。

直接看效果圖:

示例中只需在 XML 布局裡添加 tools 命名空間的 text 屬性即可,這個屬性與正式發布的版本完全無關,是不是很酷?

使用前,先在根布局添加 tools 命名空間:

<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    ... >

用法很簡單,用 tools 命名空間替代 android 命名空間即可,例如:

<ListView
    android:id="@+id/listView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fastScrollAlwaysVisible="true"
    tools:fastScrollAlwaysVisible="" />

也可以這樣用:

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="First"
    tools:visibility="invisible" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Second"
    tools:visibility="visible" />

需要注意的是,tools 屬性只能在 layout 文件中使用,而且只能用於 framework 自帶的屬性,無法用於自定義屬性。不過這已經足以覆蓋我們絕大多數的預覽需求了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved