Fragment在Android3.0開始提供,而且在兼容包中也提供了Fragment特性的支持。

Fragment的推出让我们编写和管理用户界面更快捷更方便了。


但当我们实例化自己定义Fragment时,为什么官方推荐Fragment.setArguments(Bundle bundle)这样的方式来传递參数,而不推荐通过构造方法直接来传递參数呢?为了弄清这个问题,我们能够做一个測试。分别測试下这两种方式的不同

首先。我们来測试下通过构造方法传递參数的情况

  1. public class FramentTestActivity extends ActionBarActivity {
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout.activity_main);
  6. if (savedInstanceState == null) {
  7. getSupportFragmentManager().beginTransaction()
  8. .add(R.id.container, new TestFragment("param")).commit();
  9. }
  10. }
  11. public static class TestFragment extends Fragment {
  12. private String mArg = "non-param";
  13. public TestFragment() {
  14. Log.i("INFO", "TestFragment non-parameter constructor");
  15. }
  16. public TestFragment(String arg){
  17. mArg = arg;
  18. Log.i("INFO", "TestFragment construct with parameter");
  19. }
  20. @Override
  21. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  22. Bundle savedInstanceState) {
  23. View rootView = inflater.inflate(R.layout.fragment_main, container,
  24. false);
  25. TextView tv = (TextView) rootView.findViewById(R.id.tv);
  26. tv.setText(mArg);
  27. return rootView;
  28. }
  29. }
  30. }

能够看到我们传递过来的数据正确的显示了。如今来考虑一个问题。假设设备配置參数发生变化,这里以横竖屏切换来说明问题,显演示样例如以下



发生了什么问题呢?我们传递的參数哪去了?为什么会显示默认值?不急着讨论这个问题。接下来我们来看看Fragment.setArguments(Bundle bundle)这样的方式的执行情况

  1. public class FramentTest2Activity extends ActionBarActivity {
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout. activity_main);
  6. if (savedInstanceState == null) {
  7. getSupportFragmentManager().beginTransaction()
  8. .add(R.id. container, TestFragment.newInstance("param")).commit();
  9. }
  10. }
  11. public static class TestFragment extends Fragment {
  12. private static final String ARG = "arg";
  13. public TestFragment() {
  14. Log. i("INFO", "TestFragment non-parameter constructor" );
  15. }
  16. public static Fragment newInstance(String arg){
  17. TestFragment fragment = new TestFragment();
  18. Bundle bundle = new Bundle();
  19. bundle.putString( ARG, arg);
  20. fragment.setArguments(bundle);
  21. return fragment;
  22. }
  23. @Override
  24. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  25. Bundle savedInstanceState) {
  26. View rootView = inflater.inflate(R.layout. fragment_main, container,
  27. false);
  28. TextView tv = (TextView) rootView.findViewById(R.id. tv);
  29. tv.setText(getArguments().getString( ARG));
  30. return rootView;
  31. }
  32. }
  33. }


我们再来看看横竖屏切换后的执行情况

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdHVfYmluZ2Jpbmc=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" style="border:none; max-width:100%">


看到了吧,我们传递的參数在横竖屏切换的情况下完善保存了下来,正确的显示给用户
那么这究竟是怎么回事呢,我们知道设备横竖屏切换的话,当前展示给用户的Activity默认情况下会又一次创建并展现给用户,那依附于Activity的Fragment会进行怎样处理呢,我们能够通过源代码来查看
先来看看Activity的onCreate(Bundle saveInstance)方法

  1. protected void onCreate(Bundle savedInstanceState) {
  2. if (DEBUG_LIFECYCLE ) Slog.v( TAG, "onCreate " + this + ": " + savedInstanceState);
  3. if (mLastNonConfigurationInstances != null) {
  4. mAllLoaderManagers = mLastNonConfigurationInstances .loaders ;
  5. }
  6. if (mActivityInfo .parentActivityName != null) {
  7. if (mActionBar == null) {
  8. mEnableDefaultActionBarUp = true ;
  9. } else {
  10. mActionBar .setDefaultDisplayHomeAsUpEnabled( true);
  11. }
  12. }
  13. if (savedInstanceState != null) {
  14. Parcelable p = savedInstanceState.getParcelable( FRAGMENTS_TAG );
  15. mFragments .restoreAllState(p, mLastNonConfigurationInstances != null
  16. ? mLastNonConfigurationInstances .fragments : null);
  17. }
  18. mFragments .dispatchCreate();
  19. getApplication().dispatchActivityCreated( this , savedInstanceState);
  20. mCalled = true ;
  21. }

因为我们的Fragment是由FragmentManager来管理,所以能够跟进FragmentManager.restoreAllState()方法。通过对当前活动的Fragmnet找到以下的代码块

  1. for (int i=0; i<fms.mActive.length; i++) {
  2. FragmentState fs = fms.mActive[i];
  3. if (fs != null) {
  4. Fragment f = fs.instantiate(mActivity, mParent);
  5. if (DEBUG) Log.v(TAG, "restoreAllState: active #" + i + ": " + f);
  6. mActive.add(f);
  7. // Now that the fragment is instantiated (or came from being
  8. // retained above), clear mInstance in case we end up re-restoring
  9. // from this FragmentState again.
  10. fs.mInstance = null;
  11. } else {
  12. mActive.add(null);
  13. if (mAvailIndices == null) {
  14. mAvailIndices = new ArrayList<Integer>();
  15. }
  16. if (DEBUG) Log.v(TAG, "restoreAllState: avail #" + i);
  17. mAvailIndices.add(i);
  18. }
  19. }

接下来我们能够看看FragmentState.instantitate()方法的实现

  1. public Fragment instantiate(Activity activity, Fragment parent) {
  2. if (mInstance != null) {
  3. return mInstance ;
  4. }
  5. if (mArguments != null) {
  6. mArguments .setClassLoader(activity.getClassLoader());
  7. }
  8. mInstance = Fragment.instantiate(activity, mClassName , mArguments );
  9. if (mSavedFragmentState != null) {
  10. mSavedFragmentState .setClassLoader(activity.getClassLoader());
  11. mInstance .mSavedFragmentState = mSavedFragmentState ;
  12. }
  13. mInstance .setIndex(mIndex , parent);
  14. mInstance .mFromLayout = mFromLayout ;
  15. mInstance .mRestored = true;
  16. mInstance .mFragmentId = mFragmentId ;
  17. mInstance .mContainerId = mContainerId ;
  18. mInstance .mTag = mTag ;
  19. mInstance .mRetainInstance = mRetainInstance ;
  20. mInstance .mDetached = mDetached ;
  21. mInstance .mFragmentManager = activity.mFragments;
  22. if (FragmentManagerImpl.DEBUG) Log.v(FragmentManagerImpl.TAG,
  23. "Instantiated fragment " + mInstance );
  24. return mInstance ;
  25. }
能够看到终于转入到Fragment.instantitate()方法

  1. public static Fragment instantiate(Context context, String fname, Bundle args) {
  2. try {
  3. Class<?

    > clazz = sClassMap .get(fname);

  4. if (clazz == null) {
  5. // Class not found in the cache, see if it's real, and try to add it
  6. clazz = context.getClassLoader().loadClass(fname);
  7. sClassMap .put(fname, clazz);
  8. }
  9. Fragment f = (Fragment)clazz.newInstance();
  10. if (args != null) {
  11. args.setClassLoader(f.getClass().getClassLoader());
  12. f. mArguments = args;
  13. }
  14. return f;
  15. } catch (ClassNotFoundException e) {
  16. throw new InstantiationException( "Unable to instantiate fragment " + fname
  17. + ": make sure class name exists, is public, and has an"
  18. + " empty constructor that is public" , e);
  19. } catch (java.lang.InstantiationException e) {
  20. throw new InstantiationException( "Unable to instantiate fragment " + fname
  21. + ": make sure class name exists, is public, and has an"
  22. + " empty constructor that is public" , e);
  23. } catch (IllegalAccessException e) {
  24. throw new InstantiationException( "Unable to instantiate fragment " + fname
  25. + ": make sure class name exists, is public, and has an"
  26. + " empty constructor that is public" , e);
  27. }
通过此方法能够看到。终于会通过反射无參构造实例化一个新的Fragment,而且给mArgments初始化为原先的值,而原来的Fragment实例的数据都丢失了。并又一次进行了初始化

通过上面的分析,我们能够知道Activity又一次创建时,会又一次构建它所管理的Fragment,原先的Fragment的字段值将会所有丢失,可是通过Fragment.setArguments(Bundle bundle)方法设置的bundle会保留下来。所以尽量使用Fragment.setArguments(Bundle bundle)方式来传递參数

最新文章

  1. jsp取得绝对路径的方法(避免请求转发的方式导致路径错误)
  2. 支付安全基础 —— HTTPS的故事
  3. 创建 maven 本地仓库
  4. Spring 源码学习
  5. linux笔记:关机重启命令shutdown,系统运行级别init,退出登录logout
  6. 一次失败的面试——IBM电话面试
  7. MyGui笔记(1)建立第一个工程
  8. HDU1253--胜利大逃亡--HDU1240--Asteroids!--简单三维BFS
  9. jQuery动态生成不规则表格前后端
  10. 用C#实现DES加密解密解决URL参数明文的问题
  11. Spring的69个知识点
  12. Centos6.9安装部署nginx服务器
  13. Word转MD文件
  14. linux如何查看所有的用户(user)、用户组(group)、密码(password/passwd)
  15. iptables防火墙详解(二)
  16. 前端-JavaScript1-4——JavaScript之变量
  17. C语言基础入门
  18. MAC下是用brew安装Redis
  19. 1017 Queueing at Bank (25)(25 point(s))
  20. git笔记(三)

热门文章

  1. 数字证书相关技术 : Versign信任签章
  2. PHP curl 抓取AJAX异步内容
  3. [转]JavaScript异步机制详解
  4. Dragon of Loowater
  5. share_ptr
  6. ganglia组播和单播
  7. 10分钟,利用canvas画一个小的loading界面
  8. vscode - 移动端适配(cssrem)
  9. Mybatis3.x与Spring4.x整合
  10. python标准库 正则表达式(re包)