Android 中為什么要用Fragment.setArguments(Bundle bundle)來傳遞參數(shù)
Fragment在Android3.0開始提供,并且在兼容包中也提供了Fragment特性的支持。Fragment的推出讓我們編寫和管理用戶界面更快捷更方便了。
但當(dāng)我們實例化自定義Fragment時,為什么官方推薦Fragment.setArguments(Bundle bundle)這種方式來傳遞參數(shù),而不推薦通過構(gòu)造方法直接來傳遞參數(shù)呢?為了弄清這個問題,我們可以做一個測試,分別測試下這兩種方式的不同
首先,我們來測試下通過構(gòu)造方法傳遞參數(shù)的情況
public class FramentTestActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new TestFragment("param")).commit(); } } public static class TestFragment extends Fragment { private String mArg = "non-param"; public TestFragment() { Log.i("INFO", "TestFragment non-parameter constructor"); } public TestFragment(String arg){ mArg = arg; Log.i("INFO", "TestFragment construct with parameter"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); TextView tv = (TextView) rootView.findViewById(R.id.tv); tv.setText(mArg); return rootView; } } }
可以看到我們傳遞過來的數(shù)據(jù)正確的顯示了,現(xiàn)在來考慮一個問題,如果設(shè)備配置參數(shù)發(fā)生變化,這里以橫豎屏切換來說明問題,顯示如下
發(fā)生了什么問題呢?我們傳遞的參數(shù)哪去了?為什么會顯示默認(rèn)值?不急著討論這個問題,接下來我們來看看Fragment.setArguments(Bundle bundle)這種方式的運(yùn)行情況
public class FramentTest2Activity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout. activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id. container, TestFragment.newInstance("param")).commit(); } } public static class TestFragment extends Fragment { private static final String ARG = "arg"; public TestFragment() { Log. i("INFO", "TestFragment non-parameter constructor" ); } public static Fragment newInstance(String arg){ TestFragment fragment = new TestFragment(); Bundle bundle = new Bundle(); bundle.putString( ARG, arg); fragment.setArguments(bundle); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout. fragment_main, container, false); TextView tv = (TextView) rootView.findViewById(R.id. tv); tv.setText(getArguments().getString( ARG)); return rootView; } } }
我們再來看看橫豎屏切換后的運(yùn)行情況
看到了吧,我們傳遞的參數(shù)在橫豎屏切換的情況下完好保存了下來,正確的顯示給用戶
那么這到底是怎么回事呢,我們知道設(shè)備橫豎屏切換的話,當(dāng)前展示給用戶的Activity默認(rèn)情況下會重新創(chuàng)建并展現(xiàn)給用戶,那依附于Activity的Fragment會進(jìn)行如何處理呢,我們可以通過源碼來查看
先來看看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 ; }
由于我們的Fragment是由FragmentManager來管理,所以可以跟進(jìn)FragmentManager.restoreAllState()方法,通過對當(dāng)前活動的Fragmnet找到下面的代碼塊
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); } }
接下來我們可以看看FragmentState.instantitate()方法的實現(xiàn)
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 ; }
可以看到最終轉(zhuǎn)入到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); }
通過此方法可以看到,最終會通過反射無參構(gòu)造實例化一個新的Fragment,并且給mArgments初始化為原先的值,而原來的Fragment實例的數(shù)據(jù)都丟失了,并重新進(jìn)行了初始化
通過上面的分析,我們可以知道Activity重新創(chuàng)建時,會重新構(gòu)建它所管理的Fragment,原先的Fragment的字段值將會全部丟失,但是通過Fragment.setArguments(Bundle bundle)
方法設(shè)置的bundle會保留下來。所以盡量使用Fragment.setArguments(Bundle bundle)
方式來傳遞參數(shù)
以上所述是小編給大家介紹的Android 中為什么要用Fragment.setArguments(Bundle bundle)來傳遞參數(shù),希望對大家有所幫助,如果大家有任何疑問歡迎給我給我留言,小編會及時回復(fù)大家的!
- Android中傳值Intent與Bundle的區(qū)別小結(jié)
- android中Intent傳值與Bundle傳值的區(qū)別詳解
- Android 通過Intent使用Bundle傳遞對象詳細(xì)介紹
- 利用adt-bundle輕松搭建Android開發(fā)環(huán)境與Hello world(Linux)
- 利用adt-bundle輕松搭建Android開發(fā)環(huán)境與Hello world(Windows)
- Android 幾種屏幕間跳轉(zhuǎn)的跳轉(zhuǎn)Intent Bundle
- Android開發(fā) Bundle傳值的理解與使用小結(jié)
相關(guān)文章
Android控件實現(xiàn)直播App點(diǎn)贊飄心動畫
這篇文章主要為大家詳細(xì)介紹了FlowLikeView控件實現(xiàn)直播App特效之點(diǎn)贊飄心動畫,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03Android藍(lán)牙通信聊天實現(xiàn)發(fā)送和接受功能
這篇文章主要為大家詳細(xì)介紹了Android藍(lán)牙通信聊天實現(xiàn)發(fā)送和接受功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-07-07Eclipse+ADT+Android SDK搭建安卓開發(fā)環(huán)境的實現(xiàn)步驟
這篇文章主要介紹了Eclipse+ADT+Android SDK搭建安卓開發(fā)環(huán)境的實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09android用java和c實現(xiàn)查找sd卡掛載路徑(sd卡路徑)的方法
這篇文章主要介紹了android用java和c實現(xiàn)查找sd卡掛載路徑(sd卡路徑)的方法,需要的朋友可以參考下2014-02-02Android自定義照相機(jī)Camera出現(xiàn)黑屏的解決方法
這篇文章主要介紹了Android自定義照相機(jī)Camera出現(xiàn)黑屏的解決方法,分析了黑屏出現(xiàn)的原因及參考解決方法,需要的朋友可以參考下2016-08-08Android開發(fā)之使用GridView展示圖片的方法
這篇文章主要介紹了Android開發(fā)之使用GridView展示圖片的方法,涉及Android使用GridView操作圖片的布局與圖片調(diào)用功能實現(xiàn)技巧,需要的朋友可以參考下2016-01-01Android?Flutter實現(xiàn)任意拖動的控件
使用flutter開發(fā)是需要控件能拖動,比如畫板中的元素,或者工具條等,所以本文為大家準(zhǔn)備了Flutter實現(xiàn)任意拖動控件的示例代碼,希望對大家有所幫助2023-07-07