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)方式来传递參数

Android开发之Fragment传递參数的几种方法的更多相关文章

  1. android开发之Fragment加载到一个Activity中

    Fragments 是android3.0以后添加的.主要是为了方便android平板端的开发.方便适应不同大小的屏幕.此代码是为了最简单的Fragment的使用,往一个Activity中添加Frag ...

  2. Android开发之Fragment的介绍、使用及生命周期

    Fragment官网介绍-http://developer.android.com/guide/components/fragments.html 郭大神的使用实例文章:http://blog.csd ...

  3. Android开发之DatePickerDialog与TimePickerDialog的功能和使用方法具体解释

    DatePickerDialog与TimePickerDialog的功能比較简单,使用方法也非常easy.仅仅要以下两步就可以. Ø  通过newkeyword创建DatePickerDialog.T ...

  4. 【Jquery】jQuery获取URL參数的两种方法

    jQuery获取URL參数的关键是获取到URL,然后对URL进行过滤处理,取出參数. location.href是取得URL.location.search是取得URL"?"之后的 ...

  5. Android开发之Fragment

    一.Fragment生命周期: 二.动态添加Fragment的三步: 1.获得Fragment的管理者FragmentManager FragmentManager fragmentManager = ...

  6. Android开发之onMeasure(int widthMeasureSpec, int heightMeasureSpec)方法

    onMeasure()函数由包含这个View的具体的ViewGroup调用,因此值也是由其ViewGroup中传入的.子类View的这两个参数widthMeasureSpec, heightMeasu ...

  7. Android开发之ViewPager+ActionBar+Fragment实现响应式可滑动Tab

     今天我们要实现的这个效果呢,在Android的应用中十分地常见,我们可以看到下面两张图,无论是系统内置的联系人应用,还是AnyView的阅读器应用,我们总能找到这样的影子,当我们滑动屏幕时,Tab可 ...

  8. Android开发之TextView高级应用

    Android开发之TextView高级应用 我们平时使用TextView往往让它作为一个显示文字的容器,但TextView的功能并不局限于此.以下就和大家分享一下TextView的一些使用技巧. A ...

  9. android开发之 Wifi的四个类

    android开发之 Wifi的四个类 在Android中对Wifi操作,android本身提供了一些实用的包,在android.net.wifi包以下.简介一下: 大致能够分为四个基本的类ScanR ...

随机推荐

  1. 转:mac下安装Sublime Text

    转:http://blog.sina.com.cn/s/blog_559d66460101cab0.html 正版的买个license其实并不贵,定价为70美元.如果不买license,也可acces ...

  2. angular中定义全局变量及全局变量的使用

    一个例子,定义了两个变量,并且把变量显示出来: <!DOCTYPE html> <html ng-app="myApp"> <head> < ...

  3. UNIX网络编程读书笔记:recvmsg和sendmsg函数

    这两个函数是最通用的I/O函数.实际上我们可以把所有read.readv.recv和recvfrom调用替换成recvmsg调用.类似地,各种输出函数调用也可以替换成sendmsg调用. #inclu ...

  4. mysql表utf-8 字符串入库编码异常

    分析:http://www.myexception.cn/mysql/639943.html 解决方法:http://blog.sina.com.cn/s/blog_3f78232201011o26. ...

  5. 使用CopyTable工具方法在线备份HBase表

    CopyTable is a simple Apache HBase utility that, unsurprisingly, can be used for copying individual ...

  6. Python——Shell编程关于Sha-Bang(#!)

    Q. #!的名字为什么叫Sha-Bang? A. Sha-Bang是Sharp和Bang的组合词.Sharp for #, Bang for ! 类似的情况是,C#通常被称为C Sharp Q. Sh ...

  7. 安卓手机使用Fiddler抓获HTTPS报文方法

    Configure Fiddler Click Tools > Fiddler Options > Connections. Ensure that the checkbox by All ...

  8. 〖Android〗(CM10.2)Android4.2/4.3中的boot.img打包方法(合适三星exynos4 CPU)

    #!/bin/bash - #=============================================================================== # # F ...

  9. 文字选中的js实现

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  10. 通用的sql语句

    1.插入: INSERT INTO 表名称 VALUES (值1, 值2,....) 我们也可以指定所要插入数据的列: INSERT INTO table_name (列1, 列2,...) VALU ...