fragment的整理

来源:互联网 发布:qq游戏网络不稳定 编辑:程序博客网 时间:2024/06/08 04:49
1 静态创建
1 创建一个类继承Fragment
2在Activity的xml文件中使用<fragment>进行配置,id,name必须写(id作为唯一标识)
3 可以在自定义类中实现想要显示的内容

2 动态创建
1 在Activity的xml文件中,先用一个<framlayout >占一个位置
2 自定义实现Fragment
3 创建一个FragmentManager, 使用getSupportFragmentManager获取对象
4 使用FragmentManager的beginTranslation方法开启一个事务
5 使用FragmentTranslation进行add,replace,show(Fragment),hidden(Fragemnt)等操作,将fragment添加到占位布局中,或者取代,隐藏等。
注意:一个碎片只可以添加 提交一次;用新的替换旧的,如果没把旧的添加到回退栈,旧的会被销毁;如果添加到回退栈,只销毁视图(DestoryView)。
6执行commit()提交。

系统设置发生改变 ,如 横竖屏改变,系统会调用无参的构造函数,

3 传值的三种方式
1 getActivity: 不建议
2 构造函数传值: 不建议 当系统设置发生改变,会调用一个无参构造函数,然后值就会消失。
3 Bundle
4 接口回调
/***
*** 使用Bundle传递
**/
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
//在调用显示碎片相关方法之前,可以通过setArgument方法传入Bundle对象
FragmentContent fc = new FragmentContent("老夫聊发少年狂, 一树梨花压海棠");
//构造一个Bundler对象,并put相关数据
Bundle bundle = new Bundle();
bundle.putString("poet", "宽衣解带进罗帷, 含羞带笑把灯吹");
fc.setArguments(bundle);
ft.replace(R.id.containerId, fc);
ft.commit();
***************************************************************************************************/**
* 第二种传值方式:setArguments和getArguments方法
* 1 在Activity中动态添加Fragment之前,先调用setArguments(Bundle)向Fragment中传入一个Bundler对象
* 2 在Fragment中调用getArguments方法,取出之前传入的Bundle对象
* 3 从Bundle对象中取出相应的数据
*/
private void passValueSecond() {
Bundle bundle = getArguments();
//说明显示碎片之前,调用过setArguments方法
if(bundle != null) {
String poet = bundle.getString("poet");
Toast.makeText(getActivity(), "poet is " + poet, Toast.LENGTH_SHORT).show();
}
}


4 fragment生命周期

标题栏列表为:默认加载左右各一个fragment




0 0
原创粉丝点击