初识Fragment

一、什么叫Fragmet
Android 3.0 引入Fragment,中文意思叫做碎片,又称为Activity的片段。
引入原因:
为了适应大屏幕的平板电脑,使用Fragment简化大屏的UI设计,对UI进行分组,模块化管理,从而更加方便地在运行过程中动态更新Activity的用户界面。需要嵌套在Activity中使用。虽然Fragment拥有自己的生命周期,但是还是受到它所在的Activity的生命周期控制。

例子:
如下图简单的新闻浏览界面,使用2个Fragment分别显示新闻列表与新闻内容,可以实现点击左边的Fragment新闻列表,右边的Fragment显示对于的新闻内容。
可以看下面的图,以上两种分别是对应平板与手机的不同情况

二、Fragment的生命周期

常用重写的几个方法:
onAttach(Activity) 
当Fragment与Activity发生关联时调用。 
onCreateView(LayoutInflater   inflater, ViewGroup,Bundle) 
创建该Fragment的视图 
onActivityCreated(Bundle) 
当Activity的onCreate方法返回时调用 
onDestoryView() 
与onCreateView想对应,当该Fragment的视图被移除时调用 
onDetach() 
与onAttach相对应,当Fragment与Activity关联被取消时调用 
注意:除了onCreateView,其他的所有方法如果你重写了,必须调用父类对于该方法的实现

三、创建Fragment的流程
Fragment的子类有:
对话框:DialogFragment      
列表:ListFragment    
选项设置:PreferenceFragment       
WebView界面:WebViewFragment

1.)静态加载
创建Fragment的xml布局文件
创建一个类继承Fragment,同时实现 onCreateView(LayoutInflater inflater, ViewGroup,Bundle) 方法,在方法中inflater.inflate()加载布局文件,返回View
在需要加载Fragment的Activity的布局文件中<fragment>的name属性为全类名。即包名+fragment的名字,例如: com.examole.fragment1
Activity调用 setContentView()加载即可

2.)动态加载
获得FragmentManager对象,通过getFragmentManager()方法获得。
获得FragmentTransaction对象,通过fm.beginTransaction()获得
调用add()或者replace()加载Fragment,调用remove()移除Fragment
最后调用commit(),提交事务

四、Fragment与Activity交互
1.组件获取
在Fragment中获取Activity中的组件
getActivity().findViewById(id);

在Activity中获取Fragment中的组件
getFragmentManager().findFragmentById(tag);
标示Fragment除了在布局文件中添加id属性标志,还可以使用Tag属性对Fragment进行标记,通过findFragmentByTag()方法找到对应的Fragment。

2.数据传递
Activity传递数据给Fragment
在Activity中创建Bundle数据包,调用Fragment实例的setArguments(bundle)方法,将数据传递给Fragment。

Fragment传递数据给Activity
在Fragment中定义一个内部回调接口,让加载Fragment的Activity实现该回调接口,Fragment就可以通过回调方法传递数据了

五、Fragment管理与Fragment事务
FragmentManager(管理)
Activity管理Fragment主要依靠FragmentManager
1.通过FragmentManager的findFragmentById()方法或者findFragmentByTag()方法获得指定的Fragment,
2.调用FragmentManager的popBackStack()方法弹出后退的Fragment或者监听后台栈的变化:addOnBackStackChangedListener(listener);

FragmentTransaction(事务)
Fragment在Activity中多个操作,如增删替换等
Fragment增加
ft.add(fragment, tag);
Fragment删除
  ft.remove(fragment); 
Fragment替换
  ft.replace(containerViewId, fragment, tag); 
Fragment隐藏
 ft.hide(fragment); 
Fragment显示
  ft.show(fragment);
记着操作完毕后,commit()提交事务。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值