Android Fragment
Android Fragment(一)
Fragment官方文档(需要翻墙)
文章目录
- Android Fragment(一)
- 一、关于Fragment
- 二、Fragment生命周期
- 1.onAttach()
- 2.onCreat()
- 3.onCreateView()
- 4.onActivityCreated()
- 5.onStart()
- 6.onResume()
- 7.onPause()
- 8.onStop
- 9.onDestroyView()
- 10.onDestroy()
- 11.onDetach()
- 三、Fragment加载方式
- 1.静态加载
- 2.动态加载
一、关于Fragment
- Fragment 表示 FragmentActivity 中的行为或界面的一部分。可以在一个 Activity 中组合多个Fragment ,从而构建多窗格界面,并在多个 Activity 中重复使用某个Fragment 。可以将Fragment 视为 Activity 的模块化组成部分,它具有自己的生命周期,能接收自己的输入事件,并且您可以在 Activity 运行时添加或移除Fragment (这有点像可以在不同 Activity 中重复使用的“子 Activity”)。
- Fragment 必须始终托管在 Activity 中,其生命周期直接受宿主 Activity 生命周期的影响。例如,当 Activity 暂停时,Activity 的所有Fragment也会暂停;当 Activity 被销毁时,所有Fragment也会被销毁。不过,当 Activity 正在运行(处于已恢复生命周期状态)时,可以独立操纵每个Fragment,如添加或移除Fragment。当执行此类片段事务时,也可将其添加到由 Activity 管理的返回栈 — Activity 中的每个返回栈条目都是一条已发生Fragment事务的记录。借助返回栈,用户可以通过按返回按钮撤消Fragment事务(后退)。
- 当将Fragment作为 Activity 布局的一部分添加时,其位于 Activity 视图层次结构的某个 ViewGroup 中,并且Fragment会定义其自己的视图布局。可以通过在 Activity 的布局文件中声明Fragment,将其作为 元素插入您的 Activity 布局,或者通过将其添加到某个现有的 ViewGroup,利用应用代码将其插入布局
二、Fragment生命周期
1.onAttach()
/*** Called when a fragment is first attached to its context.* {@link #onCreate(Bundle)} will be called after this.*/@SuppressWarnings("deprecation")@MainThread@CallSuperpublic void onAttach(@NonNull Context context) {mCalled = true;final Activity hostActivity = mHost == null ? null : mHost.getActivity();if (hostActivity != null) {mCalled = false;onAttach(hostActivity);}}/*** Called when a fragment is first attached to its activity.* {@link #onCreate(Bundle)} will be called after this.** @deprecated See {@link #onAttach(Context)}.*/@SuppressWarnings({"unused", "DeprecatedIsStillUsed"})@Deprecated@MainThread@CallSuperpublic void onAttach(@NonNull Activity activity) {mCalled = true;}
onAttach 是Fragment 生命周期的第一步,它的作用
在Fragment 和 Activity 建立关联前调用(Activity 传递到此方法内)
通常在Activity 与Fragment 是宿主关系的时候,Activity 向Fragment 传递数据的时候使用
@Overridepublic void onAttach(@NonNull Context context) {super.onAttach(context);str = ((MainActivity) context).getStr(); // activity获取数据System.out.println(str);}
2.onCreat()
/*** Called to do initial creation of a fragment. This is called after* {@link #onAttach(Activity)} and before* {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.** <p>Note that this can be called while the fragment's activity is* still in the process of being created. As such, you can not rely* on things like the activity's content view hierarchy being initialized* at this point. If you want to do work once the activity itself is* created, add a {@link androidx.lifecycle.LifecycleObserver} on the* activity's Lifecycle, removing it when it receives the* {@link Lifecycle.State#CREATED} callback.** <p>Any restored child fragments will be created before the base* <code>Fragment.onCreate</code> method returns.</p>** @param savedInstanceState If the fragment is being re-created from* a previous saved state, this is the state.*/@MainThread@CallSuperpublic void onCreate(@Nullable Bundle savedInstanceState) {mCalled = true;restoreChildFragmentState(savedInstanceState);if (!mChildFragmentManager.isStateAtLeast(Fragment.CREATED)) {mChildFragmentManager.dispatchCreate();}}
fragment初次创建时调用。尽管它看起来像是Activity的OnCreate()函数,但这个只是用来创建Fragment的。此时的Activity还没有创建完成,因为我们的Fragment也是Activity创建的一部分。
3.onCreateView()
/*** Called to have the fragment instantiate its user interface view.* This is optional, and non-graphical fragments can return null. This will be called between* {@link #onCreate(Bundle)} and {@link #onViewCreated(View, Bundle)}.* <p>A default View can be returned by calling {@link #Fragment(int)} in your* constructor. Otherwise, this method returns null.** <p>It is recommended to <strong>only</strong> inflate the layout in this method and move* logic that operates on the returned View to {@link #onViewCreated(View, Bundle)}.** <p>If you return a View from here, you will later be called in* {@link #onDestroyView} when the view is being released.** @param inflater The LayoutInflater object that can be used to inflate* any views in the fragment,* @param container If non-null, this is the parent view that the fragment's* UI should be attached to. The fragment should not add the view itself,* but this can be used to generate the LayoutParams of the view.* @param savedInstanceState If non-null, this fragment is being re-constructed* from a previous saved state as given here.** @return Return the View for the fragment's UI, or null.*/@MainThread@Nullablepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,@Nullable Bundle savedInstanceState) {if (mContentLayoutId != 0) {return inflater.inflate(mContentLayoutId, container, false);}return null;}
在这个fragment构造它的用户接口视图(即布局)时调用。
4.onActivityCreated()
/*** Called when the fragment's activity has been created and this* fragment's view hierarchy instantiated. It can be used to do final* initialization once these pieces are in place, such as retrieving* views or restoring state. It is also useful for fragments that use* {@link #setRetainInstance(boolean)} to retain their instance,* as this callback tells the fragment when it is fully associated with* the new activity instance. This is called after {@link #onCreateView}* and before {@link #onViewStateRestored(Bundle)}.** @param savedInstanceState If the fragment is being re-created from* a previous saved state, this is the state.** @deprecated use {@link #onViewCreated(View, Bundle)} for code touching* the Fragment's view and {@link #onCreate(Bundle)} for other initialization.* To get a callback specifically when a Fragment activity's* {@link Activity#onCreate(Bundle)} is called, register a* {@link androidx.lifecycle.LifecycleObserver} on the Activity's* {@link Lifecycle} in {@link #onAttach(Context)}, removing it when it receives the* {@link Lifecycle.State#CREATED} callback.*/@SuppressWarnings({"DeprecatedIsStillUsed", "unused"})@MainThread@CallSuper@Deprecatedpublic void onActivityCreated(@Nullable Bundle savedInstanceState) {mCalled = true;}
在Activity的OnCreate()结束后,会调用此方法。所以到这里的时候,Activity已经创建完成!在这个函数中才可以使用Activity的所有资源。
5.onStart()
/*** Called when the Fragment is visible to the user. This is generally* tied to {@link Activity#onStart() Activity.onStart} of the containing* Activity's lifecycle.*/@MainThread@CallSuperpublic void onStart() {mCalled = true;}
当到OnStart()时,Fragment对用户就是可见的了。但用户还未开始与Fragment交互。在生命周期中也可以看到Fragment的OnStart()过程与Activity的OnStart()过程是绑定的。意义即是一样的。
6.onResume()
/*** Called when the fragment is visible to the user and actively running.* This is generally* tied to {@link Activity#onResume() Activity.onResume} of the containing* Activity's lifecycle.*/@MainThread@CallSuperpublic void onResume() {mCalled = true;}
当这个fragment对用户可见并且正在运行时调用。这是Fragment与用户交互之前的最后一个回调。从生命周期对比中,可以看到,Fragment的OnResume与Activity的OnResume是相互绑定的,意义是一样的。它依赖于包含它的activity的Activity.onResume。当OnResume()结束后,就可以正式与用户交互了。
7.onPause()
/*** Called when the Fragment is no longer resumed. This is generally* tied to {@link Activity#onPause() Activity.onPause} of the containing* Activity's lifecycle.*/@MainThread@CallSuperpublic void onPause() {mCalled = true;}
此回调与Activity的OnPause()相绑定,与Activity的OnPause()意义一样。
8.onStop
/*** Called when the Fragment is no longer started. This is generally* tied to {@link Activity#onStop() Activity.onStop} of the containing* Activity's lifecycle.*/@MainThread@CallSuperpublic void onStop() {mCalled = true;}
这个回调与Activity的OnStop()相绑定,意义一样。已停止的Fragment可以直接返回到OnStart()回调,然后调用OnResume()。
9.onDestroyView()
/*** Called when the view previously created by {@link #onCreateView} has* been detached from the fragment. The next time the fragment needs* to be displayed, a new view will be created. This is called* after {@link #onStop()} and before {@link #onDestroy()}. It is called* <em>regardless</em> of whether {@link #onCreateView} returned a* non-null view. Internally it is called after the view's state has* been saved but before it has been removed from its parent.*/@MainThread@CallSuperpublic void onDestroyView() {mCalled = true;}
如果Fragment即将被结束或保存,那么撤销方向上的下一个回调将是onDestoryView()。会将在onCreateView创建的视图与这个fragment分离。下次这个fragment若要显示,那么将会创建新视图。这会在onStop之后和onDestroy之前调用。这个方法的调用同onCreateView是否返回非null视图无关。它会潜在的在这个视图状态被保存之后以及它被它的父视图回收之前调用。
10.onDestroy()
/*** Called when the fragment is no longer in use. This is called* after {@link #onStop()} and before {@link #onDetach()}.*/@MainThread@CallSuperpublic void onDestroy() {mCalled = true;}
当这个fragment不再使用时调用。需要注意的是,它即使经过了onDestroy()阶段,但仍然能从Activity中找到,因为它还没有Detach。
11.onDetach()
/*** Called when the fragment is no longer attached to its activity. This* is called after {@link #onDestroy()}.*/@MainThread@CallSuperpublic void onDetach() {mCalled = true;}
Fragment生命周期中最后一个回调是onDetach()。调用它以后,Fragment就不再与Activity相绑定,它也不再拥有视图层次结构,它的所有资源都将被释放。
三、Fragment加载方式
1.静态加载
MainActivity.class
public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main_activity);}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/container"android:layout_width="match_parent"android:layout_height="match_parent"><fragmentandroid:id="@+id/staticFragment"android:name="com.lw.fgmt.ui.StaticFragment"android:layout_width="match_parent"android:layout_height="match_parent"/></RelativeLayout>
StaticFragment.java
public class StaticFragment extends Fragment {@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {// Fragment的静态加载View view = inflater.inflate(R.layout.fragment_static, container, false);return view;}
}
fragment_static.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:background="#00ff00"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="fragment static load"android:textColor="#000000"android:textSize="25sp"/></LinearLayout>
2.动态加载
MainActivity.java
public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main_activity);if (savedInstanceState == null) {getSupportFragmentManager().beginTransaction().replace(R.id.container, MainFragment.newInstance()).commit();}}
}
main_activity.xml
<?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/container"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"android:orientation="horizontal"></LinearLayout>
MianFragment.java
public class MainFragment extends Fragment {public static Fragment newInstance() {return new MainFragment();}@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,@Nullable Bundle savedInstanceState) {View rootView = inflater.inflate(R.layout.main_fragment, container, false);rootView.findViewById(R.id.btnShowAnotherFragment).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {getFragmentManager().beginTransaction().addToBackStack(null) //添加到BackStack,支持返回键后退.replace(R.id.container, AnotherFragment.newInstance()).commit();}});return rootView;}
}
main_fragment.xml
<?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/main"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainFragment"><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/btnShowAnotherFragment"android:text="呈现另一个Fragment"/>
</LinearLayout>
AnotherFragment.java
public class AnotherFragment extends Fragment {public static Fragment newInstance(){return new AnotherFragment();}@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {View rootView = inflater.inflate(R.layout.another_fragment, container, false);rootView.findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {getFragmentManager().popBackStack();}});return rootView;}
}
another_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid:id="@+id/textView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="这是另一个Fragment"/><Buttonandroid:id="@+id/btnBack"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="后退" />
</LinearLayout>
Android Fragment相关推荐
- Android Fragment 基本介绍
Android Fragment 基本介绍 Android Fragment 基本介绍 Fragment Android是在Android 3.0 (API level 11)开始引入Fragment ...
- android Fragment 学习资料推荐
为什么80%的码农都做不了架构师?>>> android Fragment 学习资料推荐:android大神 郭霖 http://blog.csdn.net/guolin_ ...
- 【转】基于Android Fragment功能的例子
原文网址:http://blog.csdn.net/eyu8874521/article/details/8252216 通过最近空闲时候对Fragment的学习,尝试着写了一个小Demo,将在开发的 ...
- [转]Android fragment 重叠问题——通过hide,show方式导致的解决方法
[转]Android fragment 重叠问题--通过hide,show方式导致的解决方法 参考文章: (1)[转]Android fragment 重叠问题--通过hide,show方式导致的解决 ...
- 【转】 Android Fragment 真正的完全解析(下)
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/37992017 上篇博客中已经介绍了Fragment产生原因,以及一些基本的用法和 ...
- Android Fragment 真正的完全解析(下)
本篇将介绍上篇博客提到的:如何管理Fragment回退栈,Fragment如何与Activity交互,Fragment与Activity交互的最佳实践,没有视图的Fragment的用处,使用Fragm ...
- Android Fragment嵌套导致的bug
原文链接 Android 多个Fragment嵌套导致的三大BUG Android Fragment使用(二) 嵌套Fragments (Nested Fragments) 的使用及常见错误 http ...
- Android Fragment使用(三) Activity, Fragment, WebView的状态保存和恢复
Android中的状态保存和恢复 Android中的状态保存和恢复, 包括Activity和Fragment以及其中View的状态处理. Activity的状态除了其中的View和Fragment的状 ...
- Android Fragment 简单实例
Android上的界面展示都是通过Activity实现的.Activity实在是太经常使用了.我相信大家都已经很熟悉了,这里就不再赘述. 可是Activity也有它的局限性,相同的界面在手机上显示可能 ...
- android 底部通知,Android Fragment实现底部通知栏
Android Fragment实现底部通知栏,供大家参考,具体内容如下 截图如下: 1. 第一步先要创建fragment(动态注册) 然后将两个勾选取消掉(还有一种是自己手动创建) 会自动生成相对应 ...
最新文章
- 二流四流神经网路(模型融合矩阵乘法理论实践)
- 【Java 注解】注解简介及作用
- [数据库] Oracle使用CASE判断解决多值问题
- 并查集(加权规则、折叠规则)
- access工资明细表_《ACCESS》工资管理完整(整理).doc
- 工作58:element三级列表的问题
- 博士考试考完了,庆祝一下
- 特斯拉全自动驾驶硬件发布!马斯克明年推RoboTaxi:傻瓜才用激光雷达
- 一次磁盘满的系统故障
- vsftpd安装配置_CentOS7配置vsftpd虚拟用户模式详解
- 【渝粤教育】广东开放大学 建筑设备 形成性考核 (33)
- 【NLP】NLP数据标注工具汇总
- 猿创征文 | 国产数据库之南大通用数据库详解安装和使用
- QQ影音播放器 for Mac
- 和机器人问问题的软件_如何开发一个特定领域的自动问答机器人(Chat Bot)?
- HDR高动态范围成像
- python语言实验——某年某月的天数 OJ1160
- 本人github网址:https://github.com/HuaAndLi
- kubernetes 系列之 - 暴露运行的服务端口
- 【doris】V1.2.2安装部署单机版or集群版
热门文章
- BPG边界网关协议知识(二)
- 计算机等级考试上网怎么做,计算机基础知识上网设置篇
- Eclipse笔记-Build path entry is missing: org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.inter
- 基于队列解决柠檬水找零
- 未来计算机取代教师,顾明远:未来教育,人工智能无法替代教师和学校
- Eclipse安装windowsBuilder插件制作图形化界面
- WPF编程,TextBox回车换行的一种方法
- (附源码)计算机毕业设计SSM基于的二手车交易平台
- Java实现SRT字幕中英文合成工具
- 跟随贺老师学习道路上的收获和感受