为什么要通过Fragment.setArguments(Bundle)传递参数

Fragment在开发中是经常使用的,我们在创建一个Fragment对象实例的时候一般都会通过new Fragment()构造方法来实现。如果在创建Fragment的时候需要向其传递数据,则可以通过构造方法直接来传递参数,或者通过Fragment.setArguments(Bundle bundle)这种方式来传递参数。这两种参数传递方式大概如下:

方式一:通过构造方法传递参数

在创建Fragment的时候,使用 MyFragment fragment = new MyFragment(parameter) 来传递参数。

public class MyFragment extends Fragment {
    public MyFragment(Parameter p){
        //将参数保存起来
    }
}

方式二:通过Fragment.setArguments(Bundle)传递参数

在创建Fragment的时候,使用MyFragment fragment = MyFragment.newInstance(paramter) 来传递参数。

public class MyFragment extends Fragment {
    public static MyFragment newInstance(Parameter p) {
        MyFragment myFragment = new MyFragment();
        Bundle args = new Bundle();
        args.putInt("someParameter", p);
        myFragment.setArguments(args);
        return myFragment;
    }
}

对比分析

看上去这两种方式没有什么本质的区别,但是通过构造方法传递参数的方式是有隐患的。根据Android文档说明,当一个Fragment重新创建的时候,系统会再次调用Fragment中的默认构造函数,注意是默认构造函数。即,当你创建了一个带有参数的Fragment的之后,一旦由于什么原因(例如横竖屏切换)导致你的Fragment重新创建。那么,很遗憾,你之前传递的参数都不见了,因为recreate你的Fragment的时候,调用的是默认构造函数。因此,官方推荐使用Fragment.setArguments(Bundle bundle)这种方式来传递参数,而不推荐通过构造方法直接来传递参数。

推荐使用Fragment.setArguments(Bundle)传递参数原因

(1)Activity的onCreate(Bundle saveInstance)方法

protected void onCreate(Bundle savedInstanceState) {  
    if (DEBUG_LIFECYCLE ) Slog.v( TAG, "onCreate " + this + ": " + savedInstanceState);  
    if (mLastNonConfigurationInstances != null) {  
        mAllLoaderManagers = mLastNonConfigurationInstances .loaders ;  
    }  
    if (mActivityInfo .parentActivityName != null) {  
        if (mActionBar == null) {  
            mEnableDefaultActionBarUp = true ;  
        } else {  
            mActionBar .setDefaultDisplayHomeAsUpEnabled( true);  
        }  
    }  
    if (savedInstanceState != null) {  
        Parcelable p = savedInstanceState.getParcelable( FRAGMENTS_TAG );  
        mFragments .restoreAllState(p, mLastNonConfigurationInstances != null  
                ? mLastNonConfigurationInstances .fragments : null);  
    }  
    mFragments .dispatchCreate();  
    getApplication().dispatchActivityCreated( this , savedInstanceState);  
    mCalled = true ;  
}  

(2)跟进FragmentManager.restoreAllState()方法

  for (int i=0; i<fms.mActive.length; i++) {  
           FragmentState fs = fms.mActive[i];  
           if (fs != null) {  
              Fragment f = fs.instantiate(mActivity, mParent);  
               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<Integer>();  
               }  
               if (DEBUG) Log.v(TAG, "restoreAllState: avail #" + i);  
               mAvailIndices.add(i);  
           }  
} 

(3)跟进FragmentState.instantitate()方法

public Fragment instantiate(Activity activity, Fragment parent) {  
        if (mInstance != null) {  
            return mInstance ;  
        }  
         
        if (mArguments != null) {  
            mArguments .setClassLoader(activity.getClassLoader());  
        }  
         
        mInstance = Fragment.instantiate(activity, mClassName , mArguments );  
         
        if (mSavedFragmentState != null) {  
            mSavedFragmentState .setClassLoader(activity.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 .mFragmentManager = activity.mFragments;  
        if (FragmentManagerImpl.DEBUG) Log.v(FragmentManagerImpl.TAG,  
                "Instantiated fragment " + mInstance );  
  
        return mInstance ;  
    } 

(4)最终转入到Fragment.instantitate()方法

public static Fragment instantiate(Context context, String fname, 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);  
           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,并且给mArgments初始化为原先的值,而原来的Fragment实例的数据都丢失了,并重新进行了初始化。

通过上面的分析,我们可以知道Activity重新创建时,会重新构建它所管理的Fragment,原先的Fragment的字段值将会全部丢失,但是通过Fragment.setArguments(Bundle bundle)方法设置的bundle会保留下来,并在重建时恢复。所以,尽量使用Fragment.setArguments(Bundle bundle)方式来进行参数传递。

注意:setArguments方法的调用必须要在Fragment与Activity关联之前,即setArgument方法的使用必须要在FragmentTransaction 的commit之前使用。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,290评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,399评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,021评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,034评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,412评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,651评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,902评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,605评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,339评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,586评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,076评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,400评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,060评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,851评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,685评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,595评论 2 270

推荐阅读更多精彩内容

  • Fragment要点 1、Fragment作为Activity界面的一部分组成出现 2、可以在一个Activity...
    玉圣阅读 1,200评论 0 16
  • Fragment是什么? Fragment是Android3.0后引入的一个新的API,他出现的初衷是为了适应大屏...
    luoqiang108阅读 381评论 0 1
  • 这是一个月前写的一篇离职感言,今天恰好借这个机会发表在这里,权当自己的开篇之作。 致我可爱的朋友们: 致远者,秦8...
    涛光扬慧阅读 665评论 2 5
  • 文|心碎纸人 图|来源于网络 2017年11月11日 星期六 晴 01 “今天都在干嘛?” 晚...
    心碎纸人阅读 2,872评论 174 150
  • 月上枝头,泛起缕缕相思愁。 泪洒衣袖,难言时时离别旧。 年少不知忧,敢与天争斗。 父厉母忧爱不休, 再添几丝纹皱。...
    洁汝大弟阅读 327评论 2 6