Android开发之Fragment传递参数的几种方法

简介:
Fragment在Android3.0开始提供,并且在兼容包中也提供了Fragment特性的支持。Fragment的推出让我们编写和管理用户界面更快捷更方便了。

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

首先,我们来测试下通过构造方法传递参数的情况

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

可以看到我们传递过来的数据正确的显示了,现在来考虑一个问题,如果设备配置参数发生变化,这里以横竖屏切换来说明问题,显示如下



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

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


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



看到了吧,我们传递的参数在横竖屏切换的情况下完好保存了下来,正确的显示给用户
那么这到底是怎么回事呢,我们知道设备横竖屏切换的话,当前展示给用户的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.          
  6.         if (mArguments != null) {  
  7.             mArguments .setClassLoader(activity.getClassLoader());  
  8.         }  
  9.          
  10.         mInstance = Fragment.instantiate(activity, mClassName , mArguments );  
  11.          
  12.         if (mSavedFragmentState != null) {  
  13.             mSavedFragmentState .setClassLoader(activity.getClassLoader());  
  14.             mInstance .mSavedFragmentState = mSavedFragmentState ;  
  15.         }  
  16.         mInstance .setIndex(mIndex , parent);  
  17.         mInstance .mFromLayout = mFromLayout ;  
  18.         mInstance .mRestored = true;  
  19.         mInstance .mFragmentId = mFragmentId ;  
  20.         mInstance .mContainerId = mContainerId ;  
  21.         mInstance .mTag = mTag ;  
  22.         mInstance .mRetainInstance = mRetainInstance ;  
  23.         mInstance .mDetached = mDetached ;  
  24.         mInstance .mFragmentManager = activity.mFragments;  
  25.         if (FragmentManagerImpl.DEBUG) Log.v(FragmentManagerImpl.TAG,  
  26.                 "Instantiated fragment " + mInstance );  
  27.   
  28.         return mInstance ;  
  29.     }  

可以看到最终转入到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)方式来传递参数
相关文章
|
8月前
|
移动开发 前端开发 Android开发
【02】建立各项目录和页面标准化产品-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【02】建立各项目录和页面标准化产品-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
1479 12
【02】建立各项目录和页面标准化产品-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
|
8月前
|
移动开发 JavaScript 应用服务中间件
【06】优化完善落地页样式内容-精度优化-vue加vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【06】优化完善落地页样式内容-精度优化-vue加vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
1052 5
【06】优化完善落地页样式内容-精度优化-vue加vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
|
8月前
|
移动开发 Rust JavaScript
【01】首页建立-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【01】首页建立-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
1138 4
【01】首页建立-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
|
9月前
|
开发工具 Android开发
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
892 11
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
|
8月前
|
移动开发 Android开发
【03】建立隐私关于等相关页面和内容-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
【03】建立隐私关于等相关页面和内容-vue+vite开发实战-做一个非常漂亮的APP下载落地页-支持PC和H5自适应提供安卓苹果鸿蒙下载和网页端访问-优雅草卓伊凡
397 0
|
9月前
|
Java 开发工具 Maven
【01】完整的安卓二次商业实战-详细的初级步骤同步项目和gradle配置以及开发思路-优雅草伊凡
【01】完整的安卓二次商业实战-详细的初级步骤同步项目和gradle配置以及开发思路-优雅草伊凡
1217 6
|
11月前
|
安全 数据库 Android开发
在Android开发中实现两个Intent跳转及数据交换的方法
总结上述内容,在Android开发中,Intent不仅是活动跳转的桥梁,也是两个活动之间进行数据交换的媒介。运用Intent传递数据时需注意数据类型、传输大小限制以及安全性问题的处理,以确保应用的健壯性和安全性。
674 11
|
11月前
|
移动开发 Java 编译器
Kotlin与Jetpack Compose:Android开发生态的演进与架构思考
本文从资深Android工程师视角深入分析Kotlin与Jetpack Compose在Android系统中的技术定位。Kotlin通过空安全、协程等特性解决了Java在移动开发中的痛点,成为Android官方首选语言。Jetpack Compose则引入声明式UI范式,通过重组机制实现高效UI更新。两者结合不仅提升开发效率,更为跨平台战略和现代架构模式提供技术基础,代表了Android开发生态的根本性演进。
457 0
|
安全 Java Android开发
为什么大厂要求安卓开发者掌握Kotlin和Jetpack?深度解析现代Android开发生态优雅草卓伊凡
为什么大厂要求安卓开发者掌握Kotlin和Jetpack?深度解析现代Android开发生态优雅草卓伊凡
491 0
为什么大厂要求安卓开发者掌握Kotlin和Jetpack?深度解析现代Android开发生态优雅草卓伊凡
|
JavaScript Linux 网络安全
Termux安卓终端美化与开发实战:从下载到插件优化,小白也能玩转Linux
Termux是一款安卓平台上的开源终端模拟器,支持apt包管理、SSH连接及Python/Node.js/C++开发环境搭建,被誉为“手机上的Linux系统”。其特点包括零ROOT权限、跨平台开发和强大扩展性。本文详细介绍其安装准备、基础与高级环境配置、必备插件推荐、常见问题解决方法以及延伸学习资源,帮助用户充分利用Termux进行开发与学习。适用于Android 7+设备,原创内容转载请注明来源。
5133 77