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

Fragment 與 Activity 的通信方式及 Fragment 生命週期詳解

編輯:關於 Android 程式設計

一、Fragment 與 Activity 的通信

最推薦的做法是「接口回呼」,五步搞定:

  1. 在 Fragment 中聲明一個接口
  2. 在 Activity 中實現該接口
  3. 在 Fragment 中聲明一個接口類型的成員變量
  4. 在 Fragment 的 onAttach() 中判斷宿主 Activity 是否實現了該接口,若已實現則轉為接口對象
  5. 通過「接口對象.方法名()」調用 Activity 中的實現

Activity 側:

public class Fragment1Activity extends AppCompatActivity
        implements LeftFragment.OnFragmentInteractionListener {

    private Fragment fragment1;
    private Fragment fragment2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment1);
        getSupportActionBar().hide();
    }

    @Override
    public void changeFragment(int which) {
        switch (which) {
            case 1:
                fragment1 = new FirstFragment();
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fl, fragment1).commit();
                break;
            case 2:
                fragment2 = new SecondFragment();
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fl, fragment2).commit();
                break;
            case 3:
                if (fragment2 != null && !fragment2.isHidden()) {
                    getSupportFragmentManager().beginTransaction()
                            .hide(fragment2).commit();
                }
                break;
            case 4:
                if (fragment2 != null && fragment2.isHidden()) {
                    getSupportFragmentManager().beginTransaction()
                            .show(fragment2).commit();
                }
                break;
        }
    }
}

Activity 布局:

<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"
    tools:context="com.example.jreduch05.Fragment1Activity">

    <fragment
        android:id="@+id/top"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:name="com.example.jreduch05.fragment.TopFragment" />

    <fragment
        android:id="@+id/left"
        android:layout_width="150dp"
        android:layout_height="match_parent"
        android:layout_alignTop="@+id/fl"
        android:layout_alignParentStart="true"
        android:name="com.example.jreduch05.fragment.LeftFragment" />

    <FrameLayout
        android:id="@+id/fl"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/top"
        android:layout_toEndOf="@+id/left" />
</RelativeLayout>

LeftFragment 是通信的主角——它同時支持自己直接操作 FragmentManager,也支持通過接口把控制權交給 Activity:

public class LeftFragment extends Fragment {

    private Fragment fragment1;
    private Fragment fragment2;
    private OnFragmentInteractionListener mListener;

    public interface OnFragmentInteractionListener {
        void changeFragment(int which);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_left2, container, false);
        Button bt1 = view.findViewById(R.id.bt1);
        Button bt2 = view.findViewById(R.id.bt2);
        Button bt3 = view.findViewById(R.id.bt3);
        Button bt4 = view.findViewById(R.id.bt4);
        Button bt5 = view.findViewById(R.id.bt5);
        Button bt6 = view.findViewById(R.id.bt6);
        Button bt7 = view.findViewById(R.id.bt7);
        Button bt8 = view.findViewById(R.id.bt8);

        // 方式一:Fragment 自己動手
        bt1.setOnClickListener(v -> {
            fragment1 = new FirstFragment();
            FragmentManager fm = getFragmentManager();
            fm.beginTransaction().replace(R.id.fl, fragment1).commit();
        });
        bt2.setOnClickListener(v -> {
            fragment2 = new SecondFragment();
            FragmentManager fm = getFragmentManager();
            fm.beginTransaction().replace(R.id.fl, fragment2).commit();
        });
        bt5.setOnClickListener(v -> {
            if (fragment1 != null && !fragment1.isHidden()) {
                getFragmentManager().beginTransaction().hide(fragment1).commit();
            }
        });
        bt6.setOnClickListener(v -> {
            if (fragment1 != null && fragment1.isHidden()) {
                getFragmentManager().beginTransaction().show(fragment1).commit();
            }
        });

        // 方式二:通過接口交給 Activity 處理
        bt3.setOnClickListener(v -> mListener.changeFragment(1));
        bt4.setOnClickListener(v -> mListener.changeFragment(2));
        bt7.setOnClickListener(v -> mListener.changeFragment(3));
        bt8.setOnClickListener(v -> mListener.changeFragment(4));

        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }
}

關鍵就在 onAttach():這是 Fragment 掛上 Activity 的時刻,此時宿主已經存在,正好用來做接口綁定與類型校驗。如果宿主沒實現接口就直接拋異常,讓問題在開發期暴露,而不是等到運行時空指針。

LeftFragment 的布局就是豎排八個按鈕:

<FrameLayout 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:background="#0c04f7"
    tools:context="com.example.jreduch05.fragment.LeftFragment">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <Button android:id="@+id/bt1" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="第一個Fragment" />
        <Button android:id="@+id/bt2" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="第二個Fragment" />
        <Button android:id="@+id/bt3" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="第一個Fragment\n(Activity通信)" />
        <Button android:id="@+id/bt4" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="第二個Fragment\n(Activity通信)" />
        <Button android:id="@+id/bt5" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="隱藏Fragment1" />
        <Button android:id="@+id/bt6" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="顯示Fragment1" />
        <Button android:id="@+id/bt7" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="隱藏Fragment2\n(Activity通信)" />
        <Button android:id="@+id/bt8" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="顯示Fragment2\n(Activity通信)" />
    </LinearLayout>
</FrameLayout>

FirstFragment 演示如何接收 Activity 傳來的參數:

public class FirstFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            int ch = bundle.getInt("channel");
            TextView tv = getView().findViewById(R.id.tv);
            tv.setText(ch + "");
        }
    }
}

SecondFragment 與 MainFragment、TopFragment 結構相同,都只是簡單 inflate 一個布局,這裡不再重複貼。

運行效果:

二、Fragment 生命週期

十一個回呼的職責:

  • onAttach():Fragment 被附加到 Activity 時呼叫,可以在這裡拿到宿主 Activity
  • onCreate():Fragment 被創建時呼叫
  • :加載 Fragment 布局時呼叫
  • onActivityCreated():宿主 Activity 的 onCreate 執行完畢後呼叫
  • onStart():啟動 Fragment 時呼叫
  • onResume():Fragment 恢復時呼叫
  • onPause():Fragment 暫停時呼叫
  • onStop():Fragment 停止時呼叫
  • onDestroyView():銷毀 Fragment 中的 View 時呼叫
  • onDestroy():銷毀 Fragment 時呼叫
  • onDetach():Fragment 從 Activity 脫離時呼叫

不同操作觸發的鏈路差異明顯:

啟動時

remove 時

回退棧出棧時

按 Home、返回、鎖屏三鍵場景

驗證用的 Activity 代碼:

public class FragmentLifeActivity extends AppCompatActivity {

    private Fragment fragment;      // LifeFragment 實例
    private Fragment fragment2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_life);

        final Fragment fragment = new LifeFragment();
        Button bt1 = findViewById(R.id.bt_remove);
        Button bt2 = findViewById(R.id.bt_replace);
        Button bt3 = findViewById(R.id.bt_hide);
        Button bt4 = findViewById(R.id.bt_show);
        Button bt5 = findViewById(R.id.bt_remrep);

        bt1.setOnClickListener(v -> {
            if (fragment != null) {
                getSupportFragmentManager().beginTransaction()
                        .remove(fragment).commit();
            }
        });
        bt2.setOnClickListener(v -> {
            fragment2 = new FirstFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("channel", 1261911);
            fragment2.setArguments(bundle);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.life_frame, fragment2).commit();
        });
        bt3.setOnClickListener(v -> {
            if (fragment != null && !fragment.isHidden()) {
                getSupportFragmentManager().beginTransaction()
                        .hide(fragment).commit();
            }
        });
        bt4.setOnClickListener(v -> {
            if (fragment != null && fragment.isHidden()) {
                getSupportFragmentManager().beginTransaction()
                        .show(fragment).commit();
            }
        });
        bt5.setOnClickListener(v -> {
            if (fragment2 != null) {
                getSupportFragmentManager().beginTransaction()
                        .remove(fragment2).commit();
            }
        });

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.life_frame, fragment).commit();

        Log.d("====Activity==", "onCreate");
    }

    @Override protected void onStart()   { super.onStart();   Log.d("====Activity==", "onStart"); }
    @Override protected void onRestart() { super.onRestart(); Log.d("====Activity==", "onRestart"); }
    @Override protected void onResume()  { super.onResume();  Log.d("====Activity==", "onResume"); }
    @Override protected void onPause()   { super.onPause();   Log.d("====Activity==", "onPause"); }
    @Override protected void onStop()    { super.onStop();    Log.d("====Activity==", "onStop"); }
    @Override protected void onDestroy() { super.onDestroy(); Log.d("====Activity==", "onDestroy"); }
}

布局是一列按鈕加一個 FrameLayout 容器:

<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"
    tools:context="com.example.jreduch05.FragmentLifeActivity">

    <Button android:id="@+id/bt_remove" android:layout_width="match_parent"
            android:layout_height="wrap_content" android:text="Remove Fragment" />
    <Button android:id="@+id/bt_replace" android:layout_width="match_parent"
            android:layout_height="wrap_content" android:layout_below="@+id/bt_remove"
            android:text="Replace Fragment" />
    <Button android:id="@+id/bt_hide" android:layout_width="match_parent"
            android:layout_height="wrap_content" android:layout_below="@+id/bt_replace"
            android:text="Hide Fragment" />
    <Button android:id="@+id/bt_show" android:layout_width="match_parent"
            android:layout_height="wrap_content" android:layout_below="@+id/bt_hide"
            android:text="Show Fragment" />
    <Button android:id="@+id/bt_remrep" android:layout_width="match_parent"
            android:layout_height="wrap_content" android:layout_below="@+id/bt_show"
            android:text="removereplace" />

    <FrameLayout android:id="@+id/life_frame" android:layout_width="match_parent"
            android:layout_height="match_parent" android:layout_below="@+id/bt_remrep" />
</RelativeLayout>

實測結果:

把日誌對照一遍就能發現幾個規律:replace 會完整走一遍舊 Fragment 的銷毀鏈,而 hide/show 只走 onHiddenChanged(),不涉及生命週期方法;remove 添加回退棧後再出棧,View 會被重建,這也是為什麼 Fragment 裡的狀態需要自己在 onSaveInstanceState 中保存。

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