編輯:關於 Android 程式設計
本文示範如何在 Android 中使用 Fragment 實現介面向下一層層跳轉、並能一級級返回的效果,供大家參考。核心思路是透過自訂的返回處理介面與抽象 Fragment,讓每一層都能參與 Back 鍵的邏輯。
1. 先看專案結構圖:

2. 先定義一個 BackHandledInterface.java 介面,宣告 setSelectedFragment 方法,用於設定當前位於堆疊頂端的 Fragment;主介面 MainActivity 必須實作此介面。
package com.example.testdemo; public interface BackHandledInterface { public abstract void setSelectedFragment(BackHandledFragment selectedFragment); }
3. 定義抽象類別 BackHandledFragment 並繼承自 Fragment,後續要跳轉的 Fragment 都繼承自它。其中宣告了一個回傳 boolean 的 onBackPressed 方法,用來處理實體 Back 鍵的邏輯:若回傳 false,代表目前 Fragment 不消費返回事件,改由所屬的 FragmentActivity 處理。
package com.example.testdemo; import android.os.Bundle; import android.support.v4.app.Fragment; public abstract class BackHandledFragment extends Fragment { protected BackHandledInterface mBackHandledInterface; /** * 所有繼承BackHandledFragment的子類都將在這個方法中實現物理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,當前Fragment在棧頂 mBackHandledInterface.setSelectedFragment(this); } }
4. 主介面 MainActivity 必須繼承 FragmentActivity,才能呼叫 getSupportFragmentManager() 來管理 Fragment;同時覆寫 onBackPressed 以攔截返回鍵事件,逐層 pop 堆疊。
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) { BackHandledFragment second = fragment; FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); ft.replace(R.id.firstFragment, second, "other"); ft.addToBackStack("tag"); ft.commit(); } @Override public void setSelectedFragment(BackHandledFragment selectedFragment) { this.mBackHandedFragment = selectedFragment; } @Override public void onBackPressed() { if (mBackHandedFragment == null || !mBackHandedFragment.onBackPressed()) { if (getSupportFragmentManager().getBackStackEntryCount() == 0) { super.onBackPressed(); } else { if (getSupportFragmentManager().getBackStackEntryCount() == 1) { btnSecond.setVisibility(View.VISIBLE); } getSupportFragmentManager().popBackStack(); } } } }
5. 分別加入兩個子級 Fragment:FirstFragment.java 與 SecondFragment.java。
FirstFragment.java:在其中的按鈕上點擊後 replace 成 SecondFragment 並 addToBackStack。
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; } }
SecondFragment.java:最底層的 Fragment,onBackPressed 同樣回傳 false。
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() { return false; } }
6. 三個版面檔如下。
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 + 返回介面 + Back Stack」的組合,就能讓多層 Fragment 之間的跳轉與逐層返回變得清晰可控。希望本文對你的 Android 開發有所幫助。
ViewPager 詳解:非同步網路載入圖片+記憶體快取+導航小圓點
在 Android 應用中,歡迎引導頁、圖片輪播,或者內容多到一頁放不下需要拆成多頁時,ViewPager 都是最好用的選擇。本文用一個完整範例把它講透。範例包含三個重點
兩步打造華麗引導頁:RxJava 加持的首次啟動引導流程
前言在上一篇《基於 RxJava 實現酷炫啟動頁》中,我們用 RxJava 做了一個帶縮放動畫的啟動頁。這次要在此基礎上加一個能力:首次使用 App 時展示功能引導頁。實
Android Studio 使用心得(一):簡介與環境配置
關於 Android Studio Android Studio 在 2013 年 Google I/O 大會上首次亮相,是 Google 官方推出的全新 IDE。截至
Android L 新控件 RecyclerView 詳解與自製 Demo(多類型混排)
一、官方怎麼介紹 RecyclerView 在 Google 官方文件中,它是這樣被定義的: RecyclerView is a more advanced and fl