Fragment生命周期
Fragment是Android3.0时引入的用于解决大屏设备视图布局的一个组件。它应理解为片段或者直接就是一个块。Fragment是不能单独存在的,它必须依赖与Activity。
如何创建一个Fragment:需继承Fragment这个类,4.0之前可以使用V4兼容包的Fragment,4.0开始有单独的Fragment。
如果使用Fragment:通过以下代码加载
1 package com.baixd.app.framework.fragment; 2 3 import android.app.Fragment; 4 import android.app.FragmentManager; 5 import android.app.FragmentTransaction; 6 import android.support.v7.app.ActionBarActivity; 7 import android.os.Bundle; 8 import android.view.Menu; 9 import android.view.MenuItem; 10 import android.widget.Toast; 11 12 import com.baixd.app.framework.R; 13 14 public class CommunicationActivity extends ActionBarActivity{ 15 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.activity_communication); 20 21 FragmentManager fragmentMgr = getFragmentManager(); 22 FragmentTransaction transaction = fragmentMgr.beginTransaction(); 23 24 Fragment fragment = new CommunicationFragment(); 25 26 transaction.replace(R.id.ll_communication, fragment); 27 transaction.commit(); 28 } 29 30 }
CommunicationActivity对应的布局文件activity_communication.xml
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:paddingBottom="@dimen/activity_vertical_margin" 6 android:paddingLeft="@dimen/activity_horizontal_margin" 7 android:paddingRight="@dimen/activity_horizontal_margin" 8 android:paddingTop="@dimen/activity_vertical_margin" 9 tools:context="com.baixd.app.framework.fragment.CommunicationActivity"> 10 11 <TextView 12 android:id="@+id/tv_communication" 13 android:layout_width="wrap_content" 14 android:layout_height="wrap_content" 15 android:text="@string/hello_world" /> 16 17 <LinearLayout 18 android:id="@+id/ll_communication" 19 android:layout_width="match_parent" 20 android:layout_height="wrap_content" 21 android:layout_below="@id/tv_communication" 22 android:orientation="horizontal"> 23 24 </LinearLayout> 25 26 </RelativeLayout>
Fragment与Activity一样,也有自己的生命周期,但它的生命周期在宿主Activity内。通过代码的简单Log试验,总结他的生命周期过程如下:
1 /** 2 * 1)加载Fragment onAttach --> onCrate --> onCreateView --> onActivityCreated --> onStart --> onResume 3 * 2)按返回键 onPause --> onStop --> onDestroyView --> onDestroy --> onDetach 4 * 3)在加载了Fragment的页面内 锁屏 onPause --> onStop 5 * 4)在加载了Fragment的页面内 解锁 onStart --> onResume 6 * 5)在加载了Fragment的页面内 HOME onPause --> onStop 7 * 6)销毁activity onPause --> onStop --> onDestroyView --> onDestroy --> onDetach 8 */
分类:
Android
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了