1. Fragment 使用时要有一个无参构造函数

如果没有无参构造函数,而是像按照普通类来使用,只创建有参构造函数,则会出现 android.support.v4.app.Fragment$InstantiationException 错误。

原因:Fragment 和 Activity 都是生命周期的组件,不能看做一般的类。如果非要使用有参构造函数,可能在使用的时候第一次传参没有问题,但是大概率在后面使用的时候出现问题。因为Fragment的什么周期依附在Activity中,如果Activity为null,那么Fragment肯定不能够正常使用了,比如手机屏幕的横竖屏切换导致Activity重建了。

至于为什么是这样的呢?看下Fragment初始化的源码,有这么一段:

/**
* Create a new instance of a Fragment with the given class name. This is
* the same as calling its empty constructor.
*
* @param context The calling context being used to instantiate the fragment.
* This is currently just used to get its ClassLoader.
* @param fname The class name of the fragment to instantiate.
* @param args Bundle of arguments to supply to the fragment, which it
* can retrieve with {@link #getArguments()}. May be null.
* @return Returns a new fragment instance.
* @throws InstantiationException If there is a failure in instantiating
* the given fragment class. This is a runtime exception; it is not
* normally expected to happen.
*/
public static Fragment instantiate(Context context, String fname, @Nullable 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的创建其实也是利用了无参数的构造方法去实例化.但关键的是,它将Bundle传类新建的Fragment,这样旧的Fragment和新的Fragment就能拥有一样的Bundle,从而达到利用Bundle传递参数的目的.

查看Android的SDK文档,也给出来相关的说法:

2. 给 Fragment 传递参数

一定要使用 Bundle 方式传递参数,而不是通过重载构造函数传递参数。

public static VechileFrag newInstance(Vehicle vehicle, String userId, boolean isAdd) {
VechileFrag mf = new VechileFrag();
Bundle args = new Bundle();
args.putString("userId", userId);
args.putBoolean("isAdd", isAdd);
args.putParcelable("vehicle", vehicle);
mf.setArguments(args);
return mf;
} @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
userId = args.getString("userId");
isAdd = args.getBoolean("isAdd");
vehicle = args.getParcelable("vehicle");
if (vehicle == null) {
vehicle = new Vehicle();
}
}
}

3. Fragment 与 Activity 通信

在 Fragment 中定义一个接口和要回调的方法, Activity实现Fragment接口,需要时回调 Fragment 方法。

public IVechile mIVechile;
  public interface IVechile {
  public void submitCarSuccess(String carId, String plateNo);
  }
  @Override
  public void onAttach(Activity activity) {
    fueltypes = FuelType.getList(activity);
    try {
      mIVechile = (IVechile) activity;
    }
    catch (Exception e) {
    // TODO: handle exception     }
  }
}

Android Fragment 使用技巧的更多相关文章

  1. Android Fragment应用实战

    现在Fragment的应用真的是越来越广泛了,之前Android在3.0版本加入Fragment的时候,主要是为了解决Android Pad屏幕比较大,空间不能充分利用的问题,但现在即使只是在手机上, ...

  2. Android Fragment应用实战,使用碎片向ActivityGroup说再见

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/13171191 现在Fragment的应用真的是越来越广泛了,之前Android在3 ...

  3. 【Android自学日记】【转】Android Fragment 真正的完全解析(下)

    上篇博客中已经介绍了Fragment产生原因,以及一些基本的用法和各种API,如果你还不了解,请看:Android Fragment 真正的完全解析(上). 本篇将介绍上篇博客提到的:如何管理Frag ...

  4. 【转】你所不知道的Android Studio调试技巧

    这篇写Android studio debug技巧个人觉得写得不错,转自:http://www.jianshu.com/p/011eb88f4e0d# Android Studio目前已经成为开发An ...

  5. Android Fragment使用(四) Toolbar使用及Fragment中的Toolbar处理

    Toolbar作为ActionBar使用介绍 本文介绍了在Android中将Toolbar作为ActionBar使用的方法. 并且介绍了在Fragment和嵌套Fragment中使用Toolbar作为 ...

  6. Android Fragment使用(三) Activity, Fragment, WebView的状态保存和恢复

    Android中的状态保存和恢复 Android中的状态保存和恢复, 包括Activity和Fragment以及其中View的状态处理. Activity的状态除了其中的View和Fragment的状 ...

  7. Android Fragment使用(二) 嵌套Fragments (Nested Fragments) 的使用及常见错误

    嵌套Fragment的使用及常见错误 嵌套Fragments (Nested Fragments), 是在Fragment内部又添加Fragment. 使用时, 主要要依靠宿主Fragment的 ge ...

  8. Android Fragment使用(一) 基础篇 温故知新

    Fragment使用的基本知识点总结, 包括Fragment的添加, 参数传递和通信, 生命周期和各种操作. Fragment使用基础 Fragment添加 方法一: 布局里的标签 标识符: tag, ...

  9. Android Fragment 真正的完全解析(下)

    转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/37992017 上篇博客中已经介绍了Fragment产生原因,以及一些基本的用法和 ...

随机推荐

  1. Redis——学习之路三(初识redis config配置)

    我们先看看config 默认情况下系统是怎么配置的.在命令行中输入 config get *(如图) 默认情况下有61配置信息,每一个命令占两行,第一行为配置名称信息,第二行为配置的具体信息.     ...

  2. Android四种点击事件和五中存储方式

    Android点击事件的四种实现方式 1.内部类实现onClickListenter接口 bt_login.setOnClickListener(new MyListener()); class My ...

  3. sprint3

    Sprint 3计划会议: 团队: 郭志豪:http://www.cnblogs.com/gzh13692021053/ 杨子健:http://www.cnblogs.com/yzj666/ 刘森松: ...

  4. eclipse安装hibernate-Tools

    启动eclipse 选择Help -> About Eclipse 记住自己的eclipse版本 访问http://download.jboss.org/jbosstools/updates/s ...

  5. 爬虫研究-主要针对ali

    公司一个同事想爬取ali的网页受挫,自己跟着尝试了下,发现存在anti-spdier.准备了解下反爬虫,看怎么处理ali. http://www.freebuf.com/news/topnews/96 ...

  6. Redis_密码管理(转)

    一. 如何初始化redis的密码? 总共2个步骤: a.在配置文件中有个参数: requirepass  这个就是配置redis访问密码的参数. 比如 requirepass test123 b.配置 ...

  7. GADL配置编译

    GADL配置编译 文章1:Win7(32/64)VS2010配置编译GDAL环境(图文教程+亲测可用!) 转载:http://malagis.com/win7-vs2010-gdal.html 近的一 ...

  8. 4_jquery

    官网:www.jquery.com 兼容: 1.jquery-3.1.0.js :form.attr("checked","false")无效 2.firefo ...

  9. 一次sql排序的问题。

    select date, count(fail) as fail,count(win) as win from (select date,(case (result) when 'fail' then ...

  10. javascript的变量声明提升

    这篇随笔是对网上文章的整理吸收 1. javascript的作用域是函数,不是块 2. 在函数内部,javascript解释器会把var变量提升到当前域的最前面,但是函数体不会提升. 看下面例子: v ...