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

Activity 與 Fragment 之間的資料交換(一):三種溝通方式與動畫切換

編輯:關於 Android 程式設計

為什麼要用 Fragment?最大的好處是在單一 Activity 中就能呈現多種畫面,而且 Fragment 之間的切換動畫變化遠比 Activity 之間豐富。實務上很常見的架構就是一個 Activity 搭配多個 Fragment 輪替。

本文整理 Fragment 與其宿主 Activity 之間的三種資料交換方式,並示範以 FragmentManager 管理堆疊。

三種溝通方式

1. Fragment 直接取得 Activity 並呼叫其公開方法

((XXXXActivity) getActivity()).fun();

2. Activity 透過 setArguments() 傳值,Fragment 以 getArguments() 接收

3. 定義回呼介面,Fragment 在 onAttach() 中把 Activity 轉型為該介面,需要時再呼叫

三者之中,第一種耦合度最高、最不推薦;第二種適合 Activity → Fragment 的初始資料傳遞;第三種則是 Fragment → Activity 的正規做法。

以 FragmentManager 管理堆疊

透過 FragmentManager 管理時,Fragment 的建立與銷毀可以走堆疊模式:

a. FragmentTransaction.add() 推入一個 Fragment;
b. popBackStack() 把它彈出。

這樣使用者按返回鍵時,就能自然回到上一個 Fragment,而不會直接離開 App。

fragment1.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:background="#FFFFFFFF"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.testfragment.MainActivity$PlaceholderFragment">

    <TextView android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="fragment1" />

    <Button android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
        android:text="跳轉到 Fragment2" />
</RelativeLayout>

MyFragment1.java

package com.example.testfragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

public class MyFragment1 extends Fragment {

    FragmentCallBack fragmentCallBack = null;
    Button btn;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment1, container, false);
        btn = (Button) rootView.findViewById(R.id.btn);
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                fragmentCallBack.callbackFun1(null);
            }
        });
        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        fragmentCallBack = (MainActivity) activity;
    }
}

fragment2.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:background="#FFFFFFFF"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.testfragment.MainActivity$PlaceholderFragment">

    <TextView android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="fragment2" />

    <Button android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
        android:text="直接調用 Activity" />

    <Button android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn1"
        android:text="回調 Activity" />
</RelativeLayout>

MyFragment2.java

package com.example.testfragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class MyFragment2 extends Fragment {

    FragmentCallBack fragmentCallBack = null;
    Button btn1;
    Button btn2;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment2, container, false);

        // 取得 Activity 傳來的值
        Bundle data = getArguments();
        if (data != null) {
            Toast.makeText(getActivity(), data.getString("TEXT"), Toast.LENGTH_SHORT).show();
        }

        btn1 = (Button) rootView.findViewById(R.id.btn1);
        btn1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 直接調用 Activity 的方法
                ((MainActivity) getActivity()).changeButtonColor();
            }
        });

        btn2 = (Button) rootView.findViewById(R.id.btn2);
        btn2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 以回調方式通知 Activity
                fragmentCallBack.callbackFun2(null);
            }
        });

        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        fragmentCallBack = (MainActivity) activity;
    }
}

回呼介面 FragmentCallBack

package com.example.testfragment;

import android.os.Bundle;

public interface FragmentCallBack {
    void callbackFun1(Bundle arg);
    void callbackFun2(Bundle arg);
}

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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <Button android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="切換" />

    <RelativeLayout android:id="@+id/rl_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/btn" />
</RelativeLayout>

MainActivity.java

package com.example.testfragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends ActionBarActivity implements FragmentCallBack {

    private Button btn;
    private MyFragment1 fragment1;
    private MyFragment2 fragment2;
    private FragmentManager fragmentManager;
    private Fragment currentFragment;

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

        fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.setCustomAnimations(
                android.R.anim.fade_in, android.R.anim.fade_out);

        fragment1 = new MyFragment1();
        Bundle data = new Bundle();
        data.putString("TEXT", "這是 Activity 透過 Bundle 傳遞過來的值");
        fragment1.setArguments(data);

        fragmentTransaction.add(R.id.rl_container, fragment1);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commitAllowingStateLoss();
        currentFragment = fragment1;

        btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentFragment instanceof MyFragment1) {
                    switchFragment();
                } else {
                    // 目前是 fragment2,出棧即可回到 fragment1
                    fragmentManager.popBackStack();
                    currentFragment = fragment1;
                }
            }
        });
    }

    /** 切換 Fragment */
    private void switchFragment() {
        if (null == fragment2) {
            fragment2 = new MyFragment2();
        }
        Bundle data = new Bundle();
        data.putString("TEXT", "傳遞給 fragment2");
        fragment2.setArguments(data);

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.setCustomAnimations(
                android.R.anim.fade_in, android.R.anim.fade_out);
        fragmentTransaction.add(R.id.rl_container, fragment2);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commitAllowingStateLoss();
        currentFragment = fragment2;
    }

    public void changeButtonColor() {
        btn.setBackgroundColor(Color.RED);
    }

    @Override
    public void callbackFun1(Bundle arg) {
        switchFragment();
    }

    @Override
    public void callbackFun2(Bundle arg) {
        changeButtonColor();
    }
}

初始畫面。

切換到 Fragment2 之後,透過回呼改變按鈕背景的結果。

重點整理與進一步建議

1. 直接 getActivity() 強轉的做法不推薦。它會讓 Fragment 與特定 Activity 綁死, reused 到其他畫面時容易出問題。若不得已要這麼做,起碼先用 instanceof 判斷型別,並把強轉結果做 null 檢查——getActivity() 在 Fragment 尚未 attach 或已 detach 時會回傳 null。

2. setCustomAnimations 讓切換效果豐富許多。Fragment 切換支援的動畫組合遠多於 Activity 之間的轉場,善用 slide、fade、scale 能顯著提升操作手感。

3. 多個 Fragment 共享一個 Activity,可重複利用大量程式碼。例如共用的 Toolbar、選單、權限請求流程,都只需實作一次。

4. 也可以改用 ViewPager 管理 Fragment。透過 Adapter 掛載多個 Fragment,再以 setCurrentItem() 切換,並同樣以 setArguments() 傳遞資料。這種做法適合可左右滑動的選項卡場景。

5. 幾個容易忽略的細節:

● setArguments() 必須在 Fragment 建立之後、commit 之前呼叫。Fragment 被系統重建時 arguments 會一併還原,因此把參數放在 Bundle 而非依賴 Activity 的成員變數,才能正確走過螢幕旋轉。

● commitAllowingStateLoss() 會在狀態已保存後允許提交,代價是可能丟失這次變更。若非必要,優先行 commitNow() 或確保在生命週期安全點提交。

● onAttach 中轉型的介面引用應在 onDetach 中清空,否則 Fragment 被銷毀後 Activity 的參考仍被持有,容易造成記憶體洩漏。

● 若同時使用 add() 與 hide()/show() 而非 replace(),被隱藏的 Fragment 不會走 onDestroyView,其 View 仍佔用記憶體;在 Fragment 數量多時要留意這點。

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