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

Fragment 巢狀重複 id 崩潰解析:Binary XML file line #23: Duplicate id

編輯:關於 Android 開發

問題現場

  • 觸發時機:在首頁與分類頁之間切換,從「分類」返回「首頁」時直接閃退。

Logcat 給出的關鍵訊息是:

Caused by: java.lang.IllegalArgumentException: Binary XML file line #23: Duplicate id 0x7f0d0054,
tag null, or parent id 0xffffffff with another fragment for
com.example.sxq123.iljmall.FragmentCatagorySpace

出事的版面與程式碼

fragment_home.xml 裡用 <fragment> 標籤靜態嵌入了一個子 Fragment:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/home" />
            <fragment
                android:id="@+id/fragment_space"
                android:name="com.example.sxq123.iljmall.FragmentCatagorySpace"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>

FragmentHome.java 則在 onCreateView 中 inflate 版面並取得子 Fragment:

public class FragmentHome extends Fragment {
    private View view;
    FragmentCatagorySpace fragmentCatagorySpace;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInsataceState) {
        view = inflater.inflate(R.layout.fragment_home, null);
        Log.d(this.getClass().getName(), " onCreateView() Begin");
        initChildFragment();
        return view;
    }

    private void initChildFragment() {
        Log.d("-------------------", "init space ");
        fragmentCatagorySpace = (FragmentCatagorySpace) getChildFragmentManager()
                                  .findFragmentById(R.id.fragment_space);
        if (fragmentCatagorySpace != null) {
            Log.d("----------------", "init space success and no null");
        }
    }
}

根本原因

問題出在 FragmentManager 的替換機制。當 Activity 中的多個 Fragment 互相 replace 時,FragmentManager 只會 remove 與 add 這一層的 Fragment,卻不會遞迴去清理每個 Fragment 內部自己載入的子 Fragment。也就是說 FragmentCatagorySpace 一直留在 child FragmentManager 裡沒被移除。

這顯然是個設計上的坑:子 Fragment 明明依附在父 Fragment 上,父 Fragment 被銷毀時理應連帶遞迴清理,但系統沒有這麼做。於是當 FragmentHome 重新 onCreateView、再次 inflate 同一份帶有 <fragment> 的版面時,就多出了同一個 id 的第二個 Fragment 實例,直接拋出 Duplicate id。

解法方向很明確:在 FragmentHome 不再使用的時候,主動把它內部載入的子 Fragment 移除掉,而且這個移除動作必須在父 Fragment 重新 inflate 版面之前完成。

修正後的程式碼

把 remove 的事務放進父 Fragment 的 onDestroyView():

public class FragmentHome extends Fragment {
    private View view;
    FragmentCatagorySpace fragmentCatagorySpace;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInsataceState) {
        view = inflater.inflate(R.layout.fragment_home, null);
        Log.d(this.getClass().getName(), " onCreateView() Begin");
        initChildFragment();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (fragmentCatagorySpace != null) {
            Log.d("-------------------", "space no null");
            FragmentManager fragmentManager = getFragmentManager();
            if (fragmentManager != null && !fragmentManager.isDestroyed()) {
                final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                if (fragmentTransaction != null) {
                    fragmentTransaction.remove(fragmentCatagorySpace);
                    // commit() 與 commitAllowingStateLoss() 都是把工作丟進主執行緒佇列,非同步執行
                    //
                    // 若沒在 inflate 之前完成 remove child fragment,就會發生 duplicate id 例外
                    // fragmentTransaction.commit();
                    // 註:commit() 也可以放在 onCreateView 中執行,但偶爾會與
                    // onSaveInstanceState() 之後不可 commit 的限制相衝突
                    fragmentTransaction.commitAllowingStateLoss();

                    // 重點:立刻執行佇列中的 transaction,不要讓它停留在非同步狀態,
                    // 否則 remove 可能拖到父 Fragment 重新 onCreateView 之後才跑完,
                    // 一樣會出現 duplicate id
                    fragmentManager.executePendingTransactions();
                    Log.d("------------------", " space destroy");
                }
            }
        }
    }

    private void initChildFragment() {
        Log.d("-------------------", "init space ");
        fragmentCatagorySpace = (FragmentCatagorySpace) getChildFragmentManager()
                                  .findFragmentById(R.id.fragment_space);
        if (fragmentCatagorySpace != null) {
            Log.d("----------------", "init space success and no null");
        }
    }
}

幾個容易踩到的細節

  • 一定要搭配 executePendingTransactions()。commit 是非同步的,只 commit 不等待,remove 很可能趕不上下一次 inflate。
  • 為什麼用 commitAllowingStateLoss()。onDestroyView 的時機點落在某些狀態保存之後,直接 commit 有時會拋 IllegalStateException,改用允許狀態遺失的版本可以避開這個衝突。
  • 不要寫在 onSaveInstanceState()。這個回呼並非每個 Fragment 生命週期都一定會被呼叫,把清理邏輯放在這裡會變成「偶爾才生效」,反而更難查。
  • 另一條思路:把 <fragment> 靜態標籤改成 FrameLayout 容器,再用 FragmentTransaction 動態 add,讓子 Fragment 的生命週期完全由自己掌控,也能從根源避開這類 id 衝突。

Reference: https://www.tuicool.com/articles/FNVN3i

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