向Fragment传递参数,为什么用setArgument(),而不自定义变量再set赋值?

Posted zhangjin1120

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了向Fragment传递参数,为什么用setArgument(),而不自定义变量再set赋值?相关的知识,希望对你有一定的参考价值。

自定义变量,然后用set方法赋值,或者给构造方法赋值,会出什么问题?

设备横竖屏切换的时候,Fragment的自定义变量,数据会丢失。具体代码验证效果,这篇文章说的很清楚:屏幕旋转Fragment数据丢失

用构造方法传参,为什么会数据丢失?

设备横竖屏切换的话,当前展示给用户的Activity默认情况下会重新创建并展现给用户,依附于Activity的Fragment也会重新创建。具体过程一步一步分析:

setArguments()是如何保存数据的?

  public void setArguments(Bundle args) 
        if (mIndex >= 0) 
            throw new IllegalStateException("Fragment already active");
        
        mArguments = args;
    

首先将当前的bundle对象赋值给mArguments,mArguments是Fragment的成员变量:
Fragment.java

public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListener 
   // Construction arguments;
	Bundle mArguments;


Activity保存状态的时候会调用onSaveInstanceState方法:
Activity.java

//从这里看出mFragments是FragmentController实例
final FragmentController mFragments = FragmentController.createController(new HostCallbacks());

protected void onSaveInstanceState(Bundle outState) 
        outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());

        outState.putInt(LAST_AUTOFILL_ID, mLastAutofillId);
        // 调用saveAllState方法保存Fragment状态
        Parcelable p = mFragments.saveAllState();
        if (p != null) 
            // 将结果保存到Bundle中
            outState.putParcelable(FRAGMENTS_TAG, p);
        
        if (mAutoFillResetNeeded) 
            outState.putBoolean(AUTOFILL_RESET_NEEDED, true);
            getAutofillManager().onSaveInstanceState(outState);
        
        getApplication().dispatchActivitySaveInstanceState(this, outState);
    

FragmentController.saveAllState()方法最终调用到FragmentManager的saveAllState方法中:

FragmentController.java

    public Parcelable saveAllState() 
       return mHost.mFragmentManager.saveAllState();
    

在FragmentManager.java中,把Fragment对象作为参数传递给了FragmentState:
FragmentManager.java

Parcelable saveAllState()      
        // 找到所有的存活的Fragment
        int N = mActive.size();
        // 代表Fragment状态的数组
        FragmentState[] active = new FragmentState[N];
        boolean haveFragments = false;
        for (int i=0; i<N; i++) 
            Fragment f = mActive.valueAt(i);
            if (f != null) 
                if (f.mIndex < 0) 
                    throwException(new IllegalStateException(
                            "Failure saving state: active " + f
                            + " has cleared index: " + f.mIndex));
                

                haveFragments = true;
                // 找到Fragment对象f,传递给FragmentState
                FragmentState fs = new FragmentState(f);
                active[i] = fs;
                // 保证Fragment已经创建了并且没有参数保存过
                if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) 
                // 保存Fragment的状态
                    fs.mSavedFragmentState = saveFragmentBasicState(f);
        FragmentManagerState fms = new FragmentManagerState();
        // active是上面代表Fragment状态的数组,至此,fragment的状态就被保存到了FragmentManagerState中
        fms.mActive = active;
        fms.mAdded = added;
        fms.mBackStack = backStack;
        fms.mNextFragmentIndex = mNextFragmentIndex;
        if (mPrimaryNav != null) 
            fms.mPrimaryNavActiveIndex = mPrimaryNav.mIndex;
        
        saveNonConfig();
        return fms;
    

FragmentState是Fragment的同级类,内部有一个final变量mArguments:
FragmentState.java

final class FragmentState implements Parcelable 
	...
    final Bundle mArguments;
    final boolean mHidden;

    Bundle mSavedFragmentState;

    Fragment mInstance;

    public FragmentState(Fragment frag) 
      	...
        mArguments = frag.mArguments;
        mHidden = frag.mHidden;
    


public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListener 
   // Construction arguments;
	Bundle mArguments;

总结一下:Fragment的状态信息保存到了FragmentState中,然后FragmentState又保存在FragmentManagerState中,FragmentManagerState对象被return回去,保存到了Bundle对象outState里面:

//Activity.onSaveInstance()方法

Parcelable p = mFragments.saveAllState();
if (p != null) 
	outState.putParcelable(FRAGMENTS_TAG, p);

数据保存后,又是如何取出并放入新的Fragment的?

默认情况下,屏幕旋转,android系统会销毁并重建Activity,上面分析了销毁时调用的onSaveInstanceState方法,把数据存在Bundle中,新建Activity时,Bundle会在onCreate方法中,作为入参被读取,现在分析重建时onCreate方法。
Activity.java

//从这里看出mFragments是FragmentController实例
final FragmentController mFragments = FragmentController.createController(new HostCallbacks());

protected void onCreate(@Nullable Bundle savedInstanceState) 
        if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
        if (mLastNonConfigurationInstances != null) 
            mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
        
        if (mActivityInfo.parentActivityName != null) 
            if (mActionBar == null) 
                mEnableDefaultActionBarUp = true;
             else 
                mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
            
        
        if (savedInstanceState != null) 
            Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
            //Fragment数据恢复从这里开始
            mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
                    ? mLastNonConfigurationInstances.fragments : null);
        
        mFragments.dispatchCreate();
        getApplication().dispatchActivityCreated(this, savedInstanceState);
        if (mVoiceInteractor != null) 
            mVoiceInteractor.attachActivity(this);
        
        mCalled = true;
    

FragmentController.java

    public void restoreAllState(Parcelable state, FragmentManagerNonConfig nonConfig) 
        mHost.mFragmentManager.restoreAllState(state, nonConfig);
    

在FragmentManager中,直接把Parcelable对象state ,强制转化为FragmentManagerState,然后取出其中的FragmentState:
FragmentManager.java

 void restoreAllState(Parcelable state, FragmentManagerNonConfig nonConfig) 
        // If there is no saved state at all, then there can not be
        // any nonConfig fragments either, so that is that.
        if (state == null) return;
        FragmentManagerState fms = (FragmentManagerState)state;
        if (fms.mActive == null) return;

        List<FragmentManagerNonConfig> childNonConfigs = null;

        // First re-attach any non-config instances we are retaining back
        // to their saved state, so we don't try to instantiate them again.
        ...
        
        // Build the full list of active fragments, instantiating them from
        // their saved state.
        mActive = new ArrayList<>(fms.mActive.length);
        if (mAvailIndices != null) 
            mAvailIndices.clear();
        
        for (int i=0; i<fms.mActive.length; i++) 
        	//在这里获取FragmentState实例
            FragmentState fs = fms.mActive[i];
            if (fs != null) 
                FragmentManagerNonConfig childNonConfig = null;
                if (childNonConfigs != null && i < childNonConfigs.size()) 
                    childNonConfig = childNonConfigs.get(i);
                
                //核心代码
                Fragment f = fs.instantiate(mHost, mParent, childNonConfig);
                if (DEBUG) Log.v(TAG, "restoreAllState: active #" + i + ": " + f);
                mActive.add(f);
                // Now that the fragment is instantiated (or came from being
                // retained above), clear mInstance in case we end up re-restoring
                // from this FragmentState again.
                fs.mInstance = null;
             else 
                mActive.add(null);
                if (mAvailIndices == null) 
                    mAvailIndices = new ArrayList<>();
                
                if (DEBUG) Log.v(TAG, "restoreAllState: avail #" + i);
                mAvailIndices.add(i);
            
        
        
        // Update the target of all retained fragments.
       ...

        // Build the list of currently added fragments.
       ...
        
        // Build the back stack.
        ...
    

关键代码是:

 Fragment f = fs.instantiate(mHost, mParent, childNonConfig);

在FragmentState中,再把已经在保存数据过程中赋值的mArguments作为参数,传递给Fragment.instantiate()方法:
FragmentState.java

final Bundle mArguments;
//mInstance是Fragment类型的成员变量
Fragment mInstance;

public Fragment instantiate(FragmentHostCallback host, Fragment parent,
            FragmentManagerNonConfig childNonConfig) 
        if (mInstance == null) 
            final Context context = host.getContext();
            if (mArguments != null)  mArguments是Bundle类型的成员变量
                mArguments.setClassLoader(context.getClassLoader());
            
			//这里是重新初始化
            mInstance = Fragment.instantiate(context, mClassName, mArguments);

            if (mSavedFragmentState != null) 
                mSavedFragmentState.setClassLoader(context.getClassLoader());
                mInstance.mSavedFragmentState = mSavedFragmentState;
            
            mInstance.setIndex(mIndex, parent);
            mInstance.mFromLayout = mFromLayout;
            mInstance.mRestored = true;
            mInstance.mFragmentId = mFragmentId;
            mInstance.mContainerId = mContainerId;
            mInstance.mTag = mTag;
            mInstance.mRetainInstance = mRetainInstance;
            mInstance.mDetached = mDetached;
            mInstance.mHidden = mHidden;
            mInstance.mFragmentManager = host.mFragmentManager;
            if (FragmentManagerImpl.DEBUG) Log.v(FragmentManagerImpl.TAG,
                    "Instantiated fragment " + mInstance);
        
        mInstance.mChildNonConfig = childNonConfig;
        return mInstance;
    

Fragment中,mArguments最终赋值给新建的Fragment对象f:
Fragment.java

public static Fragment instantiate(Context context, String fname, @Nullable Bundle args) 
        try 
            Class<?> clazz = sClassMap.get(fname);
            if (clazz == null) 
                // Class not found in the cache, see if it's real, and try to add it
                clazz = context.getClassLoader().loadClass(fname);
                if (!Fragment.class.isAssignableFrom(clazz)) 
                    throw new InstantiationException("Trying to instantiate a class " + fname
                            + " that is not a Fragment", new ClassCastException());
                
                sClassMap.put(fname, clazz);
            
            Fragment f = (Fragment)clazz.newInstance();
            if (args != null) 
                args.setClassLoader(f.getClass().getClassLoader());
                f.mArguments = args;
            
            return f;
         catch (ClassNotFoundException e) 
            throw new InstantiationException("Unable to instantiate fragment " + fname
                    + ": make sure class name exists, is public, and has an"
                    + " empty constructor that is public", e);
         catch (java.lang.InstantiationException e) 
            throw new InstantiationException("Unable to instantiate fragment " + fname
                    + ": make sure class name exists, is public, and has an"
                    + " empty constructor that is public", e);
         catch (IllegalAccessException e) 
            throw new InstantiationException("Unable to instantiate fragment " + fname
                    + ": make sure class name exists, is public, and has an"
                    + " empty constructor that is public", e);
        
    

根据:Fragment f = (Fragment)clazz.newInstance();可知,通过反射创建一个新的Fragment,调用的是无参构造函数,也就是默认构造函数,所以我们自定义的变量数据会丢失。
setArguments()为什么数据不会丢失? ,仔细看下面有一行关键代码:

 f.mArguments = args;

setArguments()的参数,重新赋值给了mArguments。

数据获取过程参考
数据保存过程参考

以上是关于向Fragment传递参数,为什么用setArgument(),而不自定义变量再set赋值?的主要内容,如果未能解决你的问题,请参考以下文章

Fragment相关梳理

Android - fragment之间数据传递

Fragment.setArguments()

Fragment传值为什么要通过setArguments()和Fragment的生命周期

activity 给 fragment 传递参数

Android------------fragment数据传递