Android Fragment 使用技巧
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 使用技巧的更多相关文章
- Android Fragment应用实战
现在Fragment的应用真的是越来越广泛了,之前Android在3.0版本加入Fragment的时候,主要是为了解决Android Pad屏幕比较大,空间不能充分利用的问题,但现在即使只是在手机上, ...
- Android Fragment应用实战,使用碎片向ActivityGroup说再见
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/13171191 现在Fragment的应用真的是越来越广泛了,之前Android在3 ...
- 【Android自学日记】【转】Android Fragment 真正的完全解析(下)
上篇博客中已经介绍了Fragment产生原因,以及一些基本的用法和各种API,如果你还不了解,请看:Android Fragment 真正的完全解析(上). 本篇将介绍上篇博客提到的:如何管理Frag ...
- 【转】你所不知道的Android Studio调试技巧
这篇写Android studio debug技巧个人觉得写得不错,转自:http://www.jianshu.com/p/011eb88f4e0d# Android Studio目前已经成为开发An ...
- Android Fragment使用(四) Toolbar使用及Fragment中的Toolbar处理
Toolbar作为ActionBar使用介绍 本文介绍了在Android中将Toolbar作为ActionBar使用的方法. 并且介绍了在Fragment和嵌套Fragment中使用Toolbar作为 ...
- Android Fragment使用(三) Activity, Fragment, WebView的状态保存和恢复
Android中的状态保存和恢复 Android中的状态保存和恢复, 包括Activity和Fragment以及其中View的状态处理. Activity的状态除了其中的View和Fragment的状 ...
- Android Fragment使用(二) 嵌套Fragments (Nested Fragments) 的使用及常见错误
嵌套Fragment的使用及常见错误 嵌套Fragments (Nested Fragments), 是在Fragment内部又添加Fragment. 使用时, 主要要依靠宿主Fragment的 ge ...
- Android Fragment使用(一) 基础篇 温故知新
Fragment使用的基本知识点总结, 包括Fragment的添加, 参数传递和通信, 生命周期和各种操作. Fragment使用基础 Fragment添加 方法一: 布局里的标签 标识符: tag, ...
- Android Fragment 真正的完全解析(下)
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/37992017 上篇博客中已经介绍了Fragment产生原因,以及一些基本的用法和 ...
随机推荐
- JavaScript(四) Window窗体操作
window: 属性(值或者子对象):opener:打开当前窗口的源窗口,如果当前窗口是首次启动浏览器打开的,则opener是null,可以利用这个属性来关闭源窗口. 方法(函数):事件(事先设置好的 ...
- selenium获取Cookie操作
直接贴代码: Set cookies = dr.manage().getCookies(); for (Cookie cookie : cookies) { System.out.println(&q ...
- Ubuntu14.04 CUDA8.0 CUDN4.0 NVIDIA1080 多种深度框架(懒人三步装) - 从入门到放弃
这是一个懒人快速安装教程,1080卡有点麻烦,因为cuda需要8.0.为了安装方便直接把命令写成三个shell脚本. 代码基本是http://blog.csdn.net/langb2014/artic ...
- jquery事件核心源码分析
我们从绑定事件开始,一步步往下看: 以jquery.1.8.3为例,平时通过jquery绑定事件最常用的是on方法,大概分为下面3种类型: $(target).on('click',function( ...
- Unity Android加密DLL笔记
unity mono 地址:https://github.com/Unity-Technologies/mono 下载与unity版本对应的unity mono. brew安装:http://brew ...
- Android自定义折线图
老师布置了个作业:http://www.cnblogs.com/qingxu/p/5316897.html 作业中提到的 “玩了几天以后,大家发现了一些很有意思的现象,比如黄金点在逐渐地往下移动.” ...
- elasticsearch一些常用的配置
配置了解 cluster #配置下集群的名称 cluster.name: my-application
- BOM DOM Event事件笔记....
js//获取文件标题 document.body //body document.title //网页标题 document.doctype//文档对象 document.url//路径 //服务器相 ...
- MySQL Can't connect to MySQL server on 'localhost' (10061)
run > services.msc > rightclick MySQL > properties >start 搞定
- 平凡的KTV后台,不平凡的KTV数据
之前就是说过“一个项目有很多重要的步骤以及功能”,那我们现在就来看看对于KTV项目来说:后台是处于什么样的重要作用! 首先就得了解KTV后台的一些功能了: 1.歌曲管理 .歌手管理 .设置资源路径 2 ...