最新Activity与Fragment完全理解
原文:http://blog.csdn.net/shakespeare001/article/details/51450818
Android开发中Activity和Fragment是非常重要的两个知识点,这里我们就分别归纳一下,在使用Activity和Fragment时需要注意的一些事项,特别是对于Fragment,在对其进行管理时我们要选择好的一些方式。
一、Activity要点
Activity负责展示UI给用户,负责和用户的交互操作。本部分主要对Activity的生命周期、如何保存状态信息、如何讲一个Activity设置成窗口模式、启动模式和完全退出Activity的方式,五部分进行总结。
1、生命周期
2、保存状态信息(推荐在onPause中保存)
@Overrideprotected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState);outState.putString("name","lly");}
当我们这个Activity被销毁而重新创建re-created的时候,通过onCreate(Bundle)中的参数获取到该信息,如下:
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main); if(savedInstanceState != null){ name = savedInstanceState.getString("name");}}
注意:onSaveInstanceState()方法只是在Activity“很容易被销毁的时候调用”,它并不是Activity的生命周期方法,这个调用时机是不确定的,对于点击返回按钮这种主动行为不会去调用这个方法。网上很多说在按下HOME键和旋转屏幕的时候会去调用,但是经过我测试一下,发现不管是我按下HOME键还是旋转屏幕,这个方法都没有被调用。按我理解,这个方法只有在“很容易被销毁的时候调用”,这个尺度应该是系统根据手机具体内存资源情况决定是否调用。因此官方文档中推荐在onPause中进行数据信息的保存操作。(Note that it is important to save persistent data in onPause()
instead of onSaveInstanceState(Bundle)
because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.)
3、如何将一个Activity设置成窗口的样式
- <style name= "Theme.FloatActivity" parent= "android:style/Theme.Dialog" >
- <!-- float_box为我们定义的窗口背景 ,这个不是必须的-->
- <item name="android:windowBackground" > @drawable /float_box</item>
- </style>
- <?xml version= "1.0" encoding= "utf-8" ?>
- <shape xmlns:android="http://schemas.android.com/apk/res/android" >
- <solid android:color="#ffffff" />
- <stroke android:width="3dp" android:color= "#ff000000" />
- <corners android:radius="3dp" />
- <padding android:left="10dp" android:top= "10dp" android:right= "10dp" android:bottom= "10dp" />
- </shape>
4、启动Activity的四种模式
5、完全退出程序的几种方法
- /**
- * APP管理类
- *
- */
- public class AppManager {
- private static Stack<Activity> activityStack;
- private static AppManager instance;
- private PendingIntent restartIntent;
- private AppManager() {
- }
- /**
- * 单一实例
- */
- public static AppManager getAppManager() {
- if (instance == null) {
- instance = new AppManager();
- }
- return instance;
- }
- /**
- * 添加Activity到堆栈
- */
- public void addActivity(Activity activity) {
- if (activityStack == null) {
- activityStack = new Stack<Activity>();
- }
- activityStack.add(activity);
- }
- /**
- * 获取当前Activity(堆栈中最后一个压入的)
- */
- public Activity currentActivity() {
- Activity activity = activityStack.lastElement();
- return activity;
- }
- /**
- * 结束当前Activity(堆栈中最后一个压入的)
- */
- public void finishActivity() {
- Activity activity = activityStack.lastElement();
- finishActivity(activity);
- }
- /**
- * 结束指定的Activity
- */
- public void finishActivity(Activity activity) {
- if (activity != null) {
- activityStack.remove(activity);
- activity.finish();
- activity = null;
- }
- }
- /**
- * 结束指定类名的Activity
- */
- public void finishActivity(Class<?> cls) {
- for (Activity activity : activityStack) {
- if (activity.getClass().equals(cls)) {
- finishActivity(activity);
- }
- }
- }
- /**
- * 结束所有Activity
- */
- public void finishAllActivity() {
- for (int i = 0, size = activityStack.size(); i < size; i++) {
- if (null != activityStack.get(i)) {
- activityStack.get(i).finish();
- }
- }
- activityStack.clear();
- }
- /**
- * 退出应用程序
- */
- public void exitApp(Context context) {
- try {
- finishAllActivity();
- System.exit(0);
- android.os.Process.killProcess(android.os.Process.myPid());
- } catch (Exception e) {
- }
- }
- }
二、Fragment
1、添加、移除Fragment的几种方式
- //在添加Fragment时
- FragmentManager fm = getSupportFragmentManager();
- FragmentTransaction tx = fm.beginTransaction();
- tab1Fragment = new Fragment1();
- tx.add(R.id.content, tab1Fragment,"fragment1");
- tx.commit();
- //在使用时,比如切换到tab2时
- if(tab1Fragment != null){
- tx.hide(tab1Fragment);
- tx.show(tab2Fragment);
- tx.commit();
- }else{
- tab1Fragment = (Fragment1) fm.findFragmentByTag("fragment1");
- tx.hide(tab1Fragment);
- tx.show(tab2Fragment);
- tx.commit();
- }
2、回退栈
- public class MainActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- FragmentManager fm = getSupportFragmentManager();
- FragmentTransaction tx = fm.beginTransaction();
- tx.add(R.id.content, new Fragment1(),"fragment1");
- tx.commit();
- }
- }
- public class Fragment1 extends Fragment implements OnClickListener {
- private Button mBtn;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.fragment_one, container, false);
- mBtn = (Button) view.findViewById(R.id.id_fragment_one_btn);
- mBtn.setOnClickListener(this);
- return view;
- }
- @Override
- public void onClick(View v) {
- Fragment2 fTwo = new Fragment2();
- FragmentManager fm = getFragmentManager();
- FragmentTransaction tx = fm.beginTransaction();
- tx.replace(R.id.content, fTwo, "fragment2");
- tx.addToBackStack(null); //将当前事务添加到回退栈
- tx.commit();
- }
- }
- public class Fragment2 extends Fragment implements OnClickListener {
- private Button mBtn ;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.fragment_two, container, false);
- mBtn = (Button) view.findViewById(R.id.id_fragment_two_btn);
- mBtn.setOnClickListener(this);
- return view ;
- }
- @Override
- public void onClick(View v) { //打开Fragment3
- Fragment3 fThree = new Fragment3();
- FragmentManager fm = getFragmentManager();
- FragmentTransaction tx = fm.beginTransaction();
- tx.hide(this); //隐藏当前显示的Fragment2
- tx.add(R.id.content , fThree, "fragment3"); //添加Fragment3
- tx.addToBackStack(null); //将当前事务添加到回退栈
- tx.commit();
- }
- }
3、与Activity通信
因为Fragment依附于Activity,Activity与Fragment通信,可以有以下几种办法:
(1)如果你Activity中包含自己管理的Fragment的引用,可以通过引用直接访问所有的Fragment的public方法
(2)如果Activity中没有保存任何Fragment的引用,那么没关系,每个Fragment都有一个唯一的TAG或者ID,可以通过getSupportFragmentManager().findFragmentByTag()或者findFragmentById()获得任何Fragment实例,然后进行操作。
(3)在Fragment中可以通过getActivity得到当前绑定的Activity的实例,然后进行操作。
最新Activity与Fragment完全理解相关推荐
- 安卓APP_ Fragment(2)—— Activity与Fragment的通信
摘自:安卓APP_ Fragment(2)-- Activity与Fragment的通信 作者:丶PURSUING 发布时间: 2021-04-16 17:23:44 网址:https://blog. ...
- android fragmentactivity fragment,Android:Activity与Fragment通信(99%)完美解决方案
前言 最近一直在想着能否有一种更好的方案来解决:Android中Activity与Fragment之间通信的问题,什么叫更好呢,就是能让Fragment的复用性高,性能还有好(不用反射),代码还要好维 ...
- 适合初学者入门的项目,通过对 Kotlin 的系统运用,实现的一个功能完备符合主流市场标准 App。包含知识点(MVVM 开发架构、单 Activity 多 Fragment 项目设计、暗夜模式、屏幕
fragmject 项目地址:miaowmiaow/fragmject 简介: 适合初学者入门的项目,通过对 Kotlin 的系统运用,实现的一个功能完备符合主流市场标准 App.包含知识点(MVVM ...
- Android开发帮助技巧(适用于入门)(第一部分-高效地构建项目的准备工作和Activity与Fragment的交互介绍)
平台: windows11 Android Studio 4.2.2 Build #AI-202.7660.26.42.7486908, built on June 24, 2021 Runtime ...
- activity改成fragment android,Activity转换为Fragment
Activity中加载不同的fragment / Fragment中加载不同的fragment 主Activity中加载(切换)多个fragment(也可以理解为activity 尽管Fragmen ...
- Lifecycle Activity和Fragment生命周期感知组件 LifecycleObserver MD
Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...
- Activity与Fragment的生命周期详解
在安卓中Activity与Fragment是非常相似的两个类,它们各自都拥有自己的生命周期,且都可以用来显示布局文件中的视图.其中Activity是通过setContenView()显示视图,而Fra ...
- activity中fragment 返回键不退出_优雅地处理加载中(loading),重试(retry)和无数据(empty)等...
LoadSir是一个高效易用,低碳环保,扩展性良好的加载反馈页管理框架,在加载网络或其他数据时候,根据需求切换状态页面,可添加自定义状态页面,如加载中,加载失败,无数据,网络超时,占位图,登录失效等常 ...
- 多个Activity与Fragment之间的数据传递
多个Activity与Fragment之间数据传递 问题描述 解决思路 具体解决 bug de到亲妈落泪. 问题描述 首先展示个人问题的整体框架: ActivityA:主页面,有一个PageView控 ...
- Android 如何快速定位当前页面是哪个Activity or Fragment
在日常需求开发中,经常碰到不太熟悉的模块,如何快速定位相应页面对应的Activity/Fragment ? (1)查看当前Activity :adb shell "dumpsys wind ...
最新文章
- HTML5实践 -- 使用css装饰你的图片画廊 - part2
- Eclipse启动时报错
- Springboot集成websocket实例
- python翻译程序-Python桌面应用案例:TXT文档翻译工具(源代码)
- LOOPS HDU - 3853 (概率dp):(希望通过该文章梳理自己的式子推导)
- 计算机考试一级考试基础知识,2016计算机一级考试msoffice基础知识
- jquery、javascript实现(get、post两种方式)跨域解决方法
- Android应用程序消息处理机制
- eclipse集成weblogic开发环境的搭建
- 【UE4游戏开发】安装UE4时报SU-PQR1603错误的解决方法
- Python之魔法方法详解
- c++获取数组长度查找算法_在C ++中查找数组长度
- 吴恩达机器学习课后作业
- 【CyberSecurityLearning 66】提权
- 提高电脑开机速度的方法
- 嵌入式linux调节lcd背光,背光调节的软件设计 - 基于嵌入式Linux的LCD背光调节及驱动实现...
- BUU-CRYPTO1密码学小白 25道入门题 详细解题思路
- 升级啦!二维码签到适用PC+andriod+IOS-PHP源码-开源代码
- vue视频播放插件vue-video-player
- 博客中的动态图片如何制作
热门文章
- php 获取文件加的名称
- 营销工作的七项核心能力
- java异步文件读写文件,Java AsynchronousFileChannel和Future读取文件
- 南阳oj-----D的小L(algorithm全排列用法)
- 问道手游服务器维护,问道手游2021年5月20日维护公告_问道手游2021年5月20日更新了什么_玩游戏网...
- java实验十三io_Java语言基础13—IO
- 虚拟机与ubuntu(二):连接访问
- maya前台渲染_maya前台渲染MEL
- 建模步骤_SolidWorks建模气球球拖,有步骤,新手都在找的练习题
- ai快捷键常用表_掌握这些AI常用快捷键和小技巧,提高速度