Fragment生命周期的四种状态

Fragment和Activity类似,也存在运行状态、暂停状态、停止状态和销毁状态。

  1. 运行状态:当前Fragment位于前台展示,可见,可获取焦点。
  2. 暂停状态:其他Activity位于前台,该Fragment可见,不能获取焦点。
  3. 停止状态:当前Fragment不可见,失去焦点。
  4. 销毁状态:当前Fragment被删除,或所在Activity被结束。

Fragment的回调函数

Fragment为11个,与比Activity不同的有5个。分别为:

  1. onAttach():在片段已与 Activity 关联时调用(Activity 传递到此方法内)。
  2. onCreateView():调用它可创建与片段关联的视图层次结构。
  3. onActivityCreated():在 Activity 的 onCreate() 方法已返回时调用。
  4. onDestroyView():在移除与片段关联的视图层次结构时调用。
  5. onDetach():在取消片段与 Activity 的关联时调用。

    与四种状态结合,如下图:

Fragment相当于Activity的一个片段,被包含在Activity中,一个Activity中可含有多个Fragment,一个Fragment也可以附属在多个Activity上Fragment也可包含Fragment。

结合Viewpage、TabLayout、RecyclerView实现多个Fragment的切换以及页面的滑动效果

以下为activity_main.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><com.google.android.material.tabs.TabLayoutandroid:id="@+id/tabs"android:layout_width="match_parent"android:layout_height="wrap_content" ><com.google.android.material.tabs.TabItemandroid:id="@+id/tabItem_follow"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="关注" /><com.google.android.material.tabs.TabItemandroid:id="@+id/tabItem_recommend"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="推荐" /><com.google.android.material.tabs.TabItemandroid:id="@+id/tabItem_digital"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="数码" /></com.google.android.material.tabs.TabLayout><androidx.viewpager.widget.ViewPagerandroid:id="@+id/id_page_vp"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1" /></LinearLayout>

以下为fragment_main.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/recycler_view"android:layout_width="match_parent"android:layout_height="match_parent" /><Buttonandroid:id="@+id/close_comment"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_alignParentBottom="true"android:layout_marginBottom="375dp"android:background="#0000"android:visibility="gone"tools:visibility="visible" /><FrameLayoutandroid:id="@+id/comment_frameLayout"android:layout_width="match_parent"android:layout_height="375dp"android:layout_alignParentBottom="true"android:visibility="gone" />
</RelativeLayout>

以下为video_data.xml布局文件(RecyclerView所对应的一个item的布局文件)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/line4"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:layout_marginTop="15dp"android:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="51dp"android:gravity="center_vertical"android:orientation="horizontal"><FrameLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"><com.example.testapp1.control.RoundImageButtonandroid:id="@+id/imageButton"android:layout_width="50dp"android:layout_height="50dp"android:background="@drawable/cir1"android:scaleType="fitXY" /><com.example.testapp1.control.RoundImageButtonandroid:id="@+id/imageButton1"android:layout_width="15dp"android:layout_height="15dp"android:layout_gravity="bottom|right"android:background="@drawable/cir1" /></FrameLayout><TextViewandroid:id="@+id/tv1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="5dp"android:text="某某某博主"android:textSize="8pt" /><FrameLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"><Buttonandroid:id="@+id/button4"android:layout_width="50dp"android:layout_height="30dp"android:background="#00000000"android:text="+关注"android:textColor="@color/design_default_color_error"android:textSize="6pt" /><Buttonandroid:id="@+id/button44"android:layout_width="50dp"android:layout_height="30dp"android:background="#00000000"android:text="已关注"android:textColor="@android:color/darker_gray"android:textSize="6pt"android:visibility="invisible" /></FrameLayout></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"><TextViewandroid:id="@+id/tv4"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginRight="20dp"android:ellipsize="end"android:maxEms="13"android:maxLines="2"android:text="emmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm"android:textColor="@color/black"android:textSize="10pt" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="40dp"android:gravity="center_vertical"android:orientation="horizontal"><TextViewandroid:id="@+id/tv5"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="25万次播放"android:textSize="5pt" /><FrameLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="180dp"><ImageButtonandroid:id="@+id/imageButton2"android:layout_width="20dp"android:layout_height="20dp"android:background="@mipmap/detail_sharebar_like"android:visibility="visible" /><ImageButtonandroid:id="@+id/imageButton22"android:layout_width="20dp"android:layout_height="20dp"android:background="@mipmap/detail_sharebar_likehighlighted"android:visibility="invisible" /></FrameLayout><TextViewandroid:id="@+id/tv3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="1dp"android:text="22268"android:textColor="@color/black"android:textSize="6pt" /><ImageButtonandroid:id="@+id/imageButton3"android:layout_width="23dp"android:layout_height="23dp"android:layout_marginLeft="7dp"android:background="@mipmap/comment_immersive_v4_5_white_big"tools:src="@android:drawable/ic_menu_view" /><TextViewandroid:id="@+id/tv6"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="1dp"android:text="268"android:textColor="@color/black"android:textSize="6pt" /><ImageButtonandroid:id="@+id/imageButton4"android:layout_width="23dp"android:layout_height="23dp"android:layout_marginLeft="7dp"android:background="@mipmap/halo_share_icon"tools:src="?attr/actionModeShareDrawable" /></LinearLayout></LinearLayout><VideoViewandroid:id="@+id/video_view"android:layout_width="match_parent"android:layout_height="250dp" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="80dp"android:layout_marginTop="10dp"android:gravity="center_vertical"android:orientation="horizontal"><androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/recycler_view1"android:layout_width="match_parent"android:layout_height="match_parent" /></LinearLayout><VideoViewandroid:id="@+id/video_view1"android:layout_width="match_parent"android:layout_height="250dp"android:layout_marginTop="25dp" />
</LinearLayout>

以下为MainActivity.java

public class MainActivity extends FragmentActivity {private static final String TAG = "--MainActivity---甘---";private List<Fragment> mFragmentList = new ArrayList<Fragment>();private FragmentAdapter mFragmentAdapter;private ViewPager mPageVp;private FollowVideoFragment mFollowVideoFragment;private RecommendVideoFragment mRecommendVideoFragment;private DigitalVideoFragment mDigitalVideoFragment;@Overrideprotected void onCreate(Bundle savedInstanceState) {Log.i(TAG, "-----------onCreate-------------");super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mPageVp = this.findViewById(R.id.id_page_vp);//绑定viewpage与TabLayoutTabLayout tabLayout = findViewById(R.id.tabs);mPageVp.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mPageVp));init();}private void init() {mFollowVideoFragment = new FollowVideoFragment();mRecommendVideoFragment = new RecommendVideoFragment();mDigitalVideoFragment = new DigitalVideoFragment();mFragmentList.add(mFollowVideoFragment);mFragmentList.add(mRecommendVideoFragment);mFragmentList.add(mDigitalVideoFragment);mFragmentAdapter = new FragmentAdapter(this.getSupportFragmentManager(), mFragmentList);mPageVp.setAdapter(mFragmentAdapter);mPageVp.setCurrentItem(1);}@Overrideprotected void onStart() {super.onStart();Log.i(TAG, "-----------onStart-------------");}@Overrideprotected void onRestart() {super.onRestart();Log.i(TAG, "-----------onRestart-------------");}@Overrideprotected void onResume() {super.onResume();Log.i(TAG, "-----------onResume-------------");}@Overrideprotected void onPause() {super.onPause();Log.i(TAG, "-----------onPause-------------");}@Overrideprotected void onStop() {super.onStop();Log.i(TAG, "-----------onStop-------------");}@Overrideprotected void onDestroy() {super.onDestroy();Log.i(TAG, "-----------onDestroy-------------");}}

以下为FollowVideoFragment.java

public class FollowVideoFragment extends Fragment {private static final String TAG = "--FollowVideoFragment---甘---";@Overridepublic void onAttach(@NonNull Context context) {Log.i(TAG,"--------onAttach---------");super.onAttach(context);}@Overridepublic void onCreate(@Nullable Bundle savedInstanceState) {Log.i(TAG, "--------onCreate---------");super.onCreate(savedInstanceState);}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {Log.i(TAG, "--------onCreateView---------");super.onCreateView(inflater, container, savedInstanceState);View videoView = inflater.inflate(R.layout.fragment_main, container, false);//此处通过RecyclerView实现页面的滑动效果RecyclerView recyclerView = videoView.findViewById(R.id.recycler_view);recyclerView.setHasFixedSize(true);LinearLayoutManager layoutManager = new LinearLayoutManager(videoView.getContext());layoutManager.setOrientation(LinearLayoutManager.VERTICAL);recyclerView.setLayoutManager(layoutManager);recyclerView.setAdapter(adapter);return videoView;}@Overridepublic void onActivityCreated(Bundle savedInstanceState) {Log.i(TAG, "--------onActivityCreated---------");super.onActivityCreated(savedInstanceState);}@Overridepublic void onStart() {Log.i(TAG, "--------onStart---------");super.onStart();}@Overridepublic void onResume() {Log.i(TAG, "--------onResume---------");super.onResume();}@Overridepublic void onPause() {Log.i(TAG, "--------onPause---------");super.onPause();}@Overridepublic void onStop() {Log.i(TAG, "--------onStop---------");super.onStop();}@Overridepublic void onDestroyView() {Log.i(TAG, "--------onDestroyView---------");super.onDestroyView();}@Overridepublic void onDestroy() {Log.i(TAG, "--------onDestroy---------");super.onDestroy();}@Overridepublic void onDetach() {Log.i(TAG, "--------onDetach---------");super.onDetach();}

其他两个Fragment的代码和FollowVideoFragment几乎一样,此处不在列出。此处三个Fragment对应同一Adapter(适配器),每一个Fragment都要有与其对应的适配器。本人在Adapter后还建立了holder用于对应一个item的绑定数据。
VideoAdapter.java

public class VideoAdapter extends RecyclerView.Adapter<VideoViewHolder> {private List<BaseData> dataList;private Context mContext;public VideoAdapter(List<BaseData> list, Context context) {dataList = list;mContext = context;}//为RecyclerView的item创建view@Overridepublic VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {View viewVideo = LayoutInflater.from(parent.getContext()).inflate(R.layout.video_data, parent, false);VideoViewHolder videoViewHolder = new VideoViewHolder(viewVideo, mContext);return videoViewHolder;}//为item绑定数据@Overridepublic void onBindViewHolder(VideoViewHolder holder, int position) {holder.bindData(dataList.get(position));}@Overridepublic int getItemCount() {return dataList.size();}
}

VideoViewHolder.java,因本人demo的实体类数据不同且需放同一list中,并为绑定数据方便,实现多态,封装了一个BaseHolder的方法,读者可将继承改为RecyclerView.ViewHolder

public class VideoViewHolder extends RecyclerView.ViewHolder<VideoData> {private VideoView videoView;TextView personName;//RoundImageButton与RoundImageButton是自定义控件RoundImageButton personHeadId;RoundImageButton personLevelid;TextView personIntroduction;TextView videoNumber;TextView goodNumber;TextView commentNumber;VideoView video1;VideoView video2;RecyclerView recyclerView;private Context mContext;@Overridepublic void bindData(VideoData videoData) {personName.setText(videoData.getName());personHeadId.setImageResource(videoData.getHeadId());personLevelid.setImageResource(videoData.getLevelId());personIntroduction.setText(videoData.getIntroduction());videoNumber.setText(videoData.getVideoNumber());goodNumber.setText(videoData.getGoodNumber());commentNumber.setText(videoData.getCommentNumber());itemView.findViewById(R.id.imageButton4).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Intent intent = new Intent(view.getContext(), NextActivity.class);view.getContext().startActivity(intent);}});}public VideoViewHolder(View view, Context mContext) {super(view);this.mContext = mContext;personName = view.findViewById(R.id.tv1);personHeadId = view.findViewById(R.id.imageButton);personLevelid = view.findViewById(R.id.imageButton1);personIntroduction = view.findViewById(R.id.tv4);videoNumber = view.findViewById(R.id.tv5);goodNumber = view.findViewById(R.id.tv3);commentNumber = view.findViewById(R.id.tv6);video1 = view.findViewById(R.id.video_view);video2 = view.findViewById(R.id.video_view1);recyclerView = view.findViewById(R.id.recycler_view1);}}

tips:以上代码可能有些绕,简单来说就是Activity包含Fragment,又因为想实现滑动效果,Fragment中包含了RecyclerView,Adapter作为适配器为RecyclerView创建item对应的view并可绑定数据(holder的代码可以放入其中),holder为item绑定数据。

通过打Log观察一个或多个Fragment的生命周期变化

一个Fragment

  1. 运行app:

  2. 按home键:

  3. 锁屏:

  4. 按返回键:

多个Fragment

  1. tablayout中默认选中中间的Fragment,此时运行APP:

  2. 滑动至FollowVideoFragment:

  3. 从FollowVideoFragment滑动至RecommendVideoFragment再滑动至DigitalVideoFragment:

  4. 在DigitalVideoFragment进行home键操作:

  5. 回到APP,在DigitalVideoFragment再进行锁屏键操作:

  6. 解锁,再按back键:

Activity的Fragment和另一个Activity之间的切换观察Fragment的生命周期

三个Fragment的生命周期变化:
MainActivity与另一个Activity的变化:

tips:Viewpage、TabLayout、RecyclerView将在笔者后续博客中。

对Fragment生命周期的理解以及其与Activity的关联相关推荐

  1. 谈谈你对Activity生命周期的理解

    谈谈你对Activity生命周期的理解 首先,为什么Activity要有生命周期呢?我觉得这是移动设备的硬件特性和交互特性决定的. 首先从硬件上来说,移动设备不像是PC平台,它的CPU.内存.电量都受 ...

  2. Fragment生命周期详解

    关于Fragment的生命周期,博主写过Activity与Fragment生命周期详解,基本上把Fragment的生命周期详细介绍过,但是那仅仅是创建一个Fragmnet时的生命周期,而事实上Frag ...

  3. Android Studio 单刷《第一行代码》系列 06 —— Fragment 生命周期

    前情提要(Previously) 本系列将使用 Android Studio 将<第一行代码>(书中讲解案例使用Eclipse)刷一遍,旨在为想入坑 Android 开发,并选择 Andr ...

  4. Fragment生命周期及其使用

    Fragment是随着Android 3.0推出时携带的一部分,若是在1.6版本中使用,必须引入相应的支持包.Fragment最大的优点是你可以根据不同设备的屏幕大小创建动态的UI.Fragment有 ...

  5. android viewpager fragment 生命周期,ViewPager中Fragment的生命周期

    网上有很多Fragment生命周期的帖子,但是看了一下,没有找到自己想了解的东西,于是决定自己动手体验一下这个生命周期.主要想了解以下几个问题: Activity中的Fragment的生命周期 Vie ...

  6. Android零基础入门第86节:探究Fragment生命周期

    2019独角兽企业重金招聘Python工程师标准>>> 一个Activity可以同时组合多个Fragment,一个Fragment也可被多个Activity 复用.Fragment可 ...

  7. android studio生命周期代码,Android Studio 单刷《第一行代码》系列 06 —— Fragment 生命周期...

    前情提要(Previously) 本系列将使用 Android Studio 将<第一行代码>(书中讲解案例使用Eclipse)刷一遍,旨在为想入坑 Android 开发,并选择 Andr ...

  8. Lifecycle Activity和Fragment生命周期感知组件 LifecycleObserver MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  9. Fragment 生命周期的详情

    Fragment每个生命周期方法的意义.作用(注意红色的不是生命周期方法): setUserVisibleHint():设置Fragment可见或者不可见时会调用此方法.在该方法里面可以通过调用get ...

最新文章

  1. 理解YOLOv2训练过程中输出参数含义
  2. Opera 扩展文章目录
  3. maven项目的依赖、继承管理
  4. 三角形内随机生成一个点
  5. Centos7 Java8的安装
  6. 如果信用卡欠款不还被坐牢,那所欠的钱还用还吗?
  7. 企业服务总线全双工异步通信机
  8. 【sping揭秘】19、关于spring中jdbctemplate中的DataSource怎么来呢
  9. 技术案例分享:WIPTEC采用Aruba边缘服务平台,实现物流配送生产自动化、精简生产力
  10. 法拉第未来宣布汉福德工厂获得最终生产使用资质
  11. 【Clickhouse】Clickhouse 表引擎之 Log系列
  12. java 注解 对象_Java基础-学习使用Annotation注解对象
  13. 1065. 最小公倍数
  14. 京东程序员回应“被猝死”;淘宝特价版已提交微信小程序;苹果 M1 单核性能勇超 Intel 11 代 i7...
  15. 画基因结构图 gggenes 用法
  16. matlab表示大于等于,matlab不等于怎么表示
  17. 计算机室教师使用制度,[最新]教师计算机室管理制度
  18. 解决SQLserver 数据库恢复挂起
  19. PDF转Markdown文件
  20. flutter基于provider状态管理设置主题颜色、实现简单登录、注册功能---页面+逻辑

热门文章

  1. SysTick定时器的一个简单应用
  2. 对GC垃圾收集的一点整理
  3. 第十期 华为拓扑-OSPF配置
  4. vim 高级使用技巧第二篇
  5. 《剑指offer》二叉树镜像
  6. 计算机网络运输层之多路复用与多路分解
  7. 网络基础——知识生活化会变得如此简单
  8. 精品软件 推荐 ACPsoft PDF Converter 免费的多功能 PDF 转换器
  9. 老男孩为网友工作疑难问题解答一例
  10. java 科学计算法