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

Android 如何保留 Fragment 的切換狀態

編輯:Android 開發教學

前言

如果每次切換都重新建立 Fragment,畫面就得重畫一次;當 Fragment 結構龐大、初始化成本高的時候,使用者會明顯感覺到卡頓。以下分享一種保留狀態的做法。

一、適用場景

1. 不使用 ViewPager;
2. 不能用 replace 切換 Fragment,因為 replace 會走到 onDestroyView,把檢視樹整個拆掉。

替代方案是用 add 一次加入全部 Fragment,切換時只控制 hide/show,這樣各頁的狀態自然被保留下來。

二、版面配置

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

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1.0" >

    </FrameLayout>

    <RadioGroup
        android:id="@+id/main_radio"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:gravity="bottom"
        android:layout_marginBottom="-6dp"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/radio_button0"
            style="@style/main_tab_bottom"
            android:drawableTop="@drawable/bottom_1" />
        <RadioButton
            android:id="@+id/radio_button1"
            style="@style/main_tab_bottom"
            android:drawableTop="@drawable/bottom_2" />
        <RadioButton
            android:id="@+id/radio_button2"
            style="@style/main_tab_bottom"
            android:drawableTop="@drawable/bottom_3" />
        <RadioButton
            android:id="@+id/radio_button3"
            style="@style/main_tab_bottom"
            android:drawableTop="@drawable/bottom_4" />
        <RadioButton
            android:id="@+id/radio_button4"
            style="@style/main_tab_bottom"
            android:drawableTop="@drawable/bottom_5" />
    </RadioGroup>
</LinearLayout>

這是很常見的結構:底部放五個 RadioButton,點擊時切換對應的 Fragment。實作時只要記住「第一次點到才 add,之後一律 hide/show」,並在切換前先隱藏目前顯示的那一個即可。

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