Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android Fragment 多級跳轉與逐級返回的完整實現方案

編輯:Android 開發實例

Fragment 的返回鍵管理是個經典難題:頁面一層層往下跳,按返回要一級級退回去,中間某一層可能還想攔截返回事件做別的事(比如先關菜單而不是退出)。本文給出一套接口 + 抽象類的清晰解法。

一、項目結構

二、BackHandledInterface:告訴 Activity「誰在棧頂」

定義一個接口,讓 Fragment 在被激活時把自己「登記」給宿主 Activity。MainActivity 需要實現它。

 package com.example.testdemo;

public interface BackHandledInterface {
    public abstract void setSelectedFragment(BackHandledFragment selectedFragment);
}

三、BackHandledFragment:把返回事件的處理權下放

抽象類中所有會參與跳轉的 Fragment 都繼承自它。關鍵設計是 onBackPressed() 返回 boolean:

返回 true 表示「這個返回事件我消費掉了」,Activity 什麼都不用做;返回 false 表示「我不處理」,交給 FragmentActivity 走默認的堆棧邏輯。

 package com.example.testdemo;

import android.os.Bundle;
import android.support.v4.app.Fragment;

public abstract class BackHandledFragment extends Fragment {

    protected BackHandledInterface mBackHandledInterface;

    /** 所有子類在這裡實現物理 Back 鍵按下後的邏輯 */
    protected abstract boolean onBackPressed();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!(getActivity() instanceof BackHandledInterface)) {
            throw new ClassCastException("Hosting Activity must implement BackHandledInterface");
        } else {
            this.mBackHandledInterface = (BackHandledInterface) getActivity();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        // 向 FragmentActivity 報告:我現在在棧頂
        mBackHandledInterface.setSelectedFragment(this);
    }
}

onStart 裡主動登記是這套方案的精髓——無論是 replace 還是硬件返回,只要 Fragment 進入啟動狀態,Activity 持有的引用就自動更新,不需要手動維護「當前是誰」。

四、MainActivity:攔截返回鍵並逐級出棧

 package com.example.testdemo;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends FragmentActivity implements BackHandledInterface {

    private static MainActivity mInstance;
    private BackHandledFragment mBackHandedFragment;
    private Button btnSecond;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSecond = (Button) findViewById(R.id.btnSecond);
        btnSecond.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                FirstFragment first = new FirstFragment();
                loadFragment(first);
                btnSecond.setVisibility(View.GONE);
            }
        });
    }

    public static MainActivity getInstance() {
        if (mInstance == null) {
            mInstance = new MainActivity();
        }
        return mInstance;
    }

    public void loadFragment(BackHandledFragment fragment) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.firstFragment, fragment, "other");
        ft.addToBackStack("tag");       // 關鍵:加入返回棧
        ft.commit();
    }

    @Override
    public void setSelectedFragment(BackHandledFragment selectedFragment) {
        this.mBackHandedFragment = selectedFragment;
    }

    @Override
    public void onBackPressed() {
        // 先給棧頂 Fragment 一次處理機會
        if (mBackHandedFragment == null || !mBackHandedFragment.onBackPressed()) {
            if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
                super.onBackPressed();          // 沒得退了,交給系統退出
            } else {
                if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
                    btnSecond.setVisibility(View.VISIBLE);  // 即將回到根界面,恢復按鈕
                }
                getSupportFragmentManager().popBackStack();
            }
        }
    }
}

五、兩個子 Fragment

FirstFragment.java——內部有一個按鈕,點擊後跳轉到 SecondFragment:

 package com.example.testdemo;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

public class FirstFragment extends BackHandledFragment {

    private View myView;
    private Button btnSecond;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        myView = inflater.inflate(R.layout.fragment_first, null);
        initView();
        return myView;
    }

    private void initView() {
        btnSecond = (Button) myView.findViewById(R.id.btnSecond);
        btnSecond.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SecondFragment second = new SecondFragment();
                FragmentManager fm = getFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.firstFragment, second);
                ft.addToBackStack("tag");
                ft.commit();
            }
        });
    }

    @Override
    protected boolean onBackPressed() {
        return false;       // 交給 Activity 處理
    }
}

SecondFragment.java——結構更簡單,示範如何把返回事件自己攔下來:

 package com.example.testdemo;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class SecondFragment extends BackHandledFragment {

    private View mView;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_second, null);
        return mView;
    }

    @Override
    protected boolean onBackPressed() {
        // 這裡可以寫:if (菜單是打開的) { 關閉菜單; return true; }
        return false;
    }
}

六、三個布局文件

activity_main.xml:

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="FragmentActivity 父界面"
        android:textSize="26sp" />

    <Button
        android:id="@+id/btnSecond"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="跳轉到 FirstFragment" />

    <FrameLayout
        android:id="@+id/firstFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>
</RelativeLayout>

fragment_first.xml:

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#e5e5e5"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="FirstFragment"
        android:textColor="#000000"
        android:textSize="26sp" />

    <Button
        android:id="@+id/btnSecond"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="打開SecondFragment" />
</RelativeLayout>

fragment_second.xml:

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#e5e5e5"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="SecondFragment"
        android:textColor="#000000"
        android:textSize="26sp" />
</RelativeLayout>

七、方案要點回顧

整套機制其實只有三個環節:Fragment 在 onStart 時自我登記;Activity 在 onBackPressed 中先詢問棧頂 Fragment;Fragment 通過返回 true/false 決定是就地消費還是讓 Activity 出棧。這樣一來,無論層級多深,返回行為都是可預期、可定製的。

需要留意的是,示例中 ft.replace 時把前一個 Fragment 直接替換掉了,如果某一層需要保留自己的視圖狀態,可以考慮改用 add/hide 組合,並在 onSaveInstanceState 中做好數據持久化。完整實例代碼可點擊此處本站下載。

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