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产生原因,以及一些基本的用法和 ...
随机推荐
- Python爬虫学习(7):浙大软院网号嗅探
软院这边网速是挺不错的,而且在宿舍和实验室都是可以通过学号直接登陆的上网的,但是..有的时候实验室的台式机需要一个网号,笔记本需要一个网号,或者再加上一个路由器需要一个,然后,感觉网号托托的不够呀.刚 ...
- svn客户端重新设置用户名和密码
在第一次使用TortoiseSVN从服务器CheckOut的时候,会要求输入用户名和密码,这时输入框下面有个选项是保存认证信息,如果选了这个选项,那么以后就不用每次都输入一遍用户名密码了. 不过,如果 ...
- http://devdocs.io/【文档收藏】
http://devdocs.io http://bower.io/ www.bower.iobrowserify.org jsPlumb布局 https://github.com/lndb/jsPl ...
- C# SQL 面试题自我总结
1,asp.net单点登录机制 2,多线程同步机制 3,写一个冒泡排序算法 4,写一个递归算法 5,字符串反转 字符串分隔后调用reverse 方法. 6,sql 中ID自动增长,查询31到40条记录 ...
- sql with as union all
WITH RPL (FId,Fname,Forder) AS ( SELECT ment.deptno,ment.deptname,ment.orderno FROM JTERP..fg_depart ...
- JQuery对象与DOM对象的区别与转换
1.jQuery对象和DOM对象的区别 DOM对象,即是我们用传统的方法(javascript)获得的对象,jQuery对象即是用jQuery类库的选择器获得的对象; eg: var domObj ...
- Java反编译代码对齐
使用反编译的代码作为jar包源码进行调试时,经常会遇到的情况是反编译后的源码之在注释里包含行号,但是与代码所在行经常对应不上.这个时候,就有必要对代码进行对齐了. public class Reo ...
- Flume_企业中日志处理
企业中的日志存放_1 201611/20161112.log.tmp 第二天文件变为20161112.log与20161113.log.tmp 拷贝一份flume-conf.properties.te ...
- PHP基础面试题
1.PHP的意思? 答:PHP是一个基于服务端来创建动态网站的脚本语言,您可以用PHP和HTML生成网站主页 2.谈谈asp,php,jsp的优缺点? 答:ASP全名Active Server Pag ...
- sscanf_强大的数据读取-转换
function <cstdio> sscanf int sscanf ( const char * s, const char * format, ...); Read formatte ...