Fragment在Android3.0開始提供,而且在兼容包中也提供了Fragment特性的支持。Fragment的推出讓咱們編寫和管理用戶界面更快捷更方便了。java
但當咱們實例化自定義Fragment時,爲何官方推薦Fragment.setArguments(Bundle bundle)這種方式來傳遞參數,而不推薦經過構造方法直接來傳遞參數呢? 爲了弄清這個問題,咱們能夠作一個測試,分別測試下這兩種方式的不一樣ide
首先,咱們來測試下經過構造方法傳遞參數的狀況測試
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; } } }
能夠看到咱們傳遞過來的數據正確的顯示了,如今來考慮一個問題,若是設備配置參數發生變化,這裏以橫豎屏切換來講明問題,顯示以下this
發生了什麼問題呢?咱們傳遞的參數哪去了?爲何會顯示默認值?不急着討論這個問題,接下來咱們來看看Fragment.setArguments(Bundle bundle)這種方式的運行狀況spa
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; } } }
咱們再來看看橫豎屏切換後的運行狀況rest
看到了吧,咱們傳遞的參數在橫豎屏切換的狀況下無缺保存了下來,正確的顯示給用戶code
那麼這究竟是怎麼回事呢,咱們知道設備橫豎屏切換的話,當前展現給用戶的Activity默認狀況下會從新建立並展示給用戶,那依附於Activity的Fragment會進行如何處理呢,咱們能夠經過源碼來查看get
先來看看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來管理,因此能夠跟進FragmentManager.restoreAllState()方法,經過對當前活動的Fragmnet找到下面的代碼塊it
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()方法的實現
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 ; }
能夠看到最終轉入到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)方式來傳遞參數