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

FlexboxLayout:Google 官方帶來的伸縮盒子布局,Android 適配新思路

編輯:關於 Android 程式設計

前陣子 GitHub 熱榜上出現了一個新面孔——Google 官方推出的 FlexboxLayout。

Flexbox 是什麼?

Flexbox 也稱彈性盒子模型或伸縮盒子模型,在前端領域早已是標配。做過 Web 的同學都清楚,Bootstrap 那套 CSS Grid 網格系統極大地提升了開發效率,也引領了響應式布局與跨平台開發的潮流。

Android 上的 FlexboxLayout 與 Bootstrap 的柵格系統形似而神不同,它更接近 CSS 裡的 Flexible Box 模塊(W3C 候選推薦標準),是一個真正意义上的彈性布局容器。

用一句話概括:子元素排列會自動伸縮、自動換行的容器控件。這解決了過去必須依賴 LinearLayout 嵌套、RelativeLayout 硬算比例,或者自定義 onMeasure 才能實現的場景。

官方示例效果

FlexboxLayout 的出現,有可能對 Android 的屏幕適配產生實質影響——布局方式靈活了,很多原本要靠百分比或嵌套層數堆出來的排列,現在用幾個屬性就能搞定。

基本用法

<com.google.android.flexbox.FlexboxLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:id="@+id/flexbox_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    app:flexWrap="wrap"
    app:alignItems="flex_start"
    app:alignContent="flex_start"
    app:flexDirection="column"
    app:justifyContent="flex_end"
    tools:showIn="@layout/activity_main">

    <TextView
        android:id="@+id/textview1"
        android:layout_width="@dimen/flex_item_length2"
        android:layout_height="@dimen/flex_item_length"
        android:text="@string/one"
        style="@style/FlexItem" />

    <TextView
        android:id="@+id/textview2"
        android:layout_width="@dimen/flex_item_length3"
        android:layout_height="@dimen/flex_item_length"
        android:text="@string/two"
        style="@style/FlexItem" />

    <TextView
        android:id="@+id/textview3"
        android:layout_width="@dimen/flex_item_length"
        android:layout_height="@dimen/flex_item_length"
        android:text="@string/three"
        style="@style/FlexItem" />

</com.google.android.flexbox.FlexboxLayout>

新增的幾個關鍵屬性

app:flexWrap="wrap" —— 子控件是否自動換行,一行擺不下就折到下一行;
app:alignItems="flex_start" —— 子控件在其所在行/列中的對齊方式(交叉軸方向);
app:alignContent="flex_start" —— 多行內容整體的對齊方式,從頭對齊還是從尾對齊;
app:flexDirection="column" —— 子控件排列方向,row 或 column,也支持 row-reverse 等倒序排列;
app:justifyContent="flex_end" —— 主軸方向上的對齊方式,可以居中、兩端對齊或末尾對齊。

此外每個子 View 還支持 layout_order、layout_flexGrow、layout_flexShrink、layout_alignSelf 等屬性,能力基本對齊 CSS Flexbox 規格。

小結

從官方示例來看,FlexboxLayout 的表達能力確實很強,尤其適合標籤流、篩選條件、卡片內元素自動換行這類布局。更多玩法還需要大家在實踐中挖掘。導入方式也很簡單,在 build.gradle 中加入 com.android.support:flexbox 依賴即可(具體版本以官方最新說明為準)。

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