Fragment

Fragment

1.什么是Fragment

他就是为了解决不同屏幕不同大小,UI重用的一个部件,他将1个activity拆分成不同小的单元,在小的单元里面定义自己的UI,最后把他们组合一起 和包含他们的activity一起共同工作

为了更好地布局以及重用一些代码。

大多数情况有UI, 可以给activity提供没有UI的提供后台行为Fragment

1.2有点

模块化(Modularity):我们不必把所有代码全部写在Activity中,而是把代码写在各自的Fragment中。

可重用(Reusability):多个Activity可以重用一个Fragment。

2.创建Fragment的方式:

1.静态 XML方式

①activity的布局xml中 添加fragment标签,并指定name属性为你创建的Fragment的子类

②在创建的Fragment中的重写onCreatView方法,返回一个从为Fragment写的布局xml中加载的View

2.动态:在代码中添加(更常用)

①activity的布局xml中 添加Fragment的占位标签,比如用FrameLayout

②获取FragmentManager ,开启事务,添加你的Fragment到第一步写的占位布局中,提交事务

3.Fragment的删除和替换

FragmentTransactionremove(Fragment f) 和replace``(int resId,Fragment f)方面

加入返回栈addToBackStack(null)

Fragment被替换后调用addToBackStack(null),按返回键,可以返回到前1个Fragment

4.Fragment的生命周期

image-20200508131501701

onAttachonAttach()

在片段已与 Activity 关联时进行调用(Activity 传递到此方法内)。

onCreateViewonCreateView()

调用它可创建与片段关联的视图层次结构。

onActivityCreatedonActivityCreated()

当 Activity 的 onCreate() 方法已返回时进行调用。

onDestroyViewonDestroyView()

在移除与片段关联的视图层次结构时进行调用。

onDetachonDetach()

在取消片段与 Activity 的关联时进行调用。

Fragment 的生命周期和 Activity 很相似,只是多了一下几个方法:
onAttach() 在Fragment 和 Activity 建立关联是调用(Activity 传递到此方法内)
onCreateView() 当Fragment 创建视图时调用
onActivityCreated() 在相关联的 Activity 的 onCreate() 方法已返回时调用。
onDestroyView() 当Fragment中的视图被移除时调用
onDetach() 当Fragment 和 Activity 取消关联时调用。

可以看下几种操作情况下Fragment 的生命周期变化

image-20200509143844383

5.系统内置的Fragment子类

5.1DialogFragment

1.继承DialogFragment,重写onCreatDialog返回一个Dialog对象

2.Activity种创建DialogFrament的子类对象,调用show()

3.演示了AlertDialog,设置日期和设置时间的Dialog

5.2ListFragment(封装了一个1个ListView)

image-20200508115949879

5.3PreferenceFragment(设置)

6.Fragment之间的通信

fragment中要更新activity的Ui,通过getActivity().findViewById是不是最佳的方法?

image-20200508105124412

1.Activity访问所属的Fragment的控件,成员变量

①拿到Fragment对象:

​ 静态的Fragment:getFragmentManager().findFragmentBy..()

​ 动态的Fragment: 直接用在activity创建的Fragment的对象的引用

②拿到Fragment的根View后找子View:fragment.getView().findViewByid(..)

2.Fragment中访问Activity的控件

  • 重写onActivityCreated()方法,在这里通过getActivity().findViewById获得并更新Activity的UI控件对象

3.Fragment与Fragment

4.Fragment与Activity之间(或其他Fragment)的通信最佳方式:

  • 不通过接口的直接在fragment中更新activity的控件这种方式和具体Actvitiy绑定较紧,高耦合,换1个activity就不能用了
  • 在发起事件的Fragment中定义interface接口,并在onAttach()方法中初始化该接口的引用变量,让其附着的Activity实现这个接口

7.android.app.Fragment 和support.v4.Fragment的区别image-20200508120505608

Fragment用法

1.静态

2.动态

3.结合viewpager


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!