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

AbsoluteLayout 為什麼不該再用:絕對定位的解析度陷阱

編輯:Android 開發教學

使用 AbsoluteLayout,可以指定其中子 View 的精確位置。以下看 main.xml:

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <Button
        android:layout_width="188dp"
        android:layout_height="wrap_content"
        android:layout_x="126px"
        android:layout_y="361px"
        android:text="Button" />

    <Button
        android:layout_width="113dp"
        android:layout_height="wrap_content"
        android:layout_x="12px"
        android:layout_y="361px"
        android:text="Button" />
</AbsoluteLayout>

效果如下,使用 android:layout_x 與 android:layout_y 屬性,把兩個 Button 放在精確的位置上:

但當 Activity 被繪製在高解析度螢幕上時,問題就出现了。以下同樣的程式碼,在高解析度螢幕上的呈現:

原因很直白:layout_x 與 layout_y 使用的是 px(實體像素),而非 dp。在解析度更高的螢幕上,同樣的像素數字代表的物理距離變小,於是元件全部擠到左上角。

正是出於這個原因,從 Android 1.5 開始,Google 官方就已不建議使用這個版面,儘管它目前仍可使用。建立 UI 時應避免 AbsoluteLayout,因為 Android 並不保證未來版本還會繼續支援它。

替代品很明確:需要絕對位置時用 ConstraintLayout 的相對約束;需要表格式排列時用 GridLayout;需要堆疊時用 FrameLayout。這幾個都能在不同解析度上正確縮放,而 AbsoluteLayout 天生做不到。

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