2019独角兽企业重金招聘Python工程师标准>>>

前面一起学习了Fragment的创建和加载,以及其生命周期方法,那么接下来进一步来学习Fragment的具体使用,本期先来学习Fragment添加、删除、替换。

一、概述

在前面的学习中,特别是动态加载的时候,有提到FragmentManager和FragmentTransaction类,这里先来详细了解一下其到底为何物。

1、FragmentManager

要管理Activity中的Fragments,就需要使用FragmentManager类。通过getFragmentManager()或getSupportFragmentManager()获得 。

FragmentManager类常用的方法有以下几个:

  • findFragmentById(int id):根据ID来找到对应的Fragment实例,主要用在静态添加Fragment的布局中,因为静态添加的Fragment才会有ID 。

  • findFragmentByTag(String tag):根据TAG找到对应的Fragment实例,主要用于在动态添加的Fragment中,根据TAG来找到Fragment实例 。

  • getFragments():获取所有被add进Activity中的Fragment 实例。

  • benginTransatcion():开启一个事物。

2、FragmentTransaction

如果需要添加、删除、替换Fragment,则需要借助于FragmentTransaction对象,FragmentTransaction 代表 Activity 对 Fragment 执行的多个改变。

FragmentTransaction类常用的方法有以下几个:

  • add(int containerViewId, Fragment fragment, String tag):将一个Fragment实例添加到Activity的最上层 。

  • remove(Fragment fragment):将一个Fragment实例从Activity的Fragment队列中删除。

  • replace(int containerViewId, Fragment fragment):替换containerViewId中的Fragment实例。注意,它首先把containerViewId中所有Fagment删除,然后再add进去当前的Fragment 实例。

  • hide(Fragment fragment):隐藏当前的Fragment,仅仅是设为不可见,并不会销毁。

  • show(Fragment fragment):显示之前隐藏的Fragment。

  • detach(Fragment fragment):会将view从UI中移除,和remove()不同,此时Fragment的状态依然由FragmentManager维护。

  • attach(Fragment fragment):重建view视图,附加到UI上并显示。

  • commit():提交一个事务。

二、示例

前面了解了Fragment管理和事物,为了更好的理解和掌握,用一个示例来进一步深度学习。

该示例非常简单,界面包含3个按钮和3个Fragment容器,其中第一个容器静态加载FirstFragment,后面两个通过动态加载的方式来完成,也是本示例主要需要学习的地方。

首先创建第一个容器的FirstFragment对应布局文件fragment_first.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="#af520b"android:orientation="vertical"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="这是我的第一个Fragment"android:textColor="#0c1ff1"android:textSize="18sp"/></LinearLayout>

接着创建第一个容器的FirstFragment文件,代码如下:

package com.cqkxzsxy.jinyu.android.fragmentbasemanager;import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;public class FirstFragment extends Fragment {@Nullable@Overridepublic View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,Bundle savedInstanceState) {View view = inflater.inflate(R.layout.fragment_first, container, false);return view;}
}

同理创建fragment_second.xml和fragment_third.xml文件,唯一的区别就是显示的提示文字和颜色不同,创建SecondFragment和ThirdFragment加载对应的布局文件,这里不在给出代码。

然后是修改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"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><Buttonandroid:id="@+id/add_btn"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="add" /><Buttonandroid:id="@+id/remove_btn"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="remove" /><Buttonandroid:id="@+id/replace_btn"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="replace" /></LinearLayout><fragmentandroid:id="@+id/fragment_one"android:name="com.cqkxzsxy.jinyu.android.fragmentbasemanager.FirstFragment"android:layout_width="match_parent"android:layout_height="wrap_content" /><FrameLayoutandroid:id="@+id/fragment_container1"android:layout_width="match_parent"android:layout_height="wrap_content" /><FrameLayoutandroid:id="@+id/fragment_container2"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout>

最后是修改MainActivity的代码,如下所示:

package com.cqkxzsxy.jinyu.android.fragmentbasemanager;import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private Button mAddBtn = null;private Button mRemoveBtn = null;private Button mReplaceBtn = null;private Fragment mSecondFragment = null;private Fragment mThirdFragment = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mAddBtn = (Button) findViewById(R.id.add_btn);mRemoveBtn = (Button) findViewById(R.id.remove_btn);mReplaceBtn = (Button) findViewById(R.id.replace_btn);// 创建和获取Fragment实例mSecondFragment = new SecondFragment();mThirdFragment = new ThirdFragment();// 设置监听事件mAddBtn.setOnClickListener(this);mRemoveBtn.setOnClickListener(this);mReplaceBtn.setOnClickListener(this);}@Overridepublic void onClick(View v) {// 获取到FragmentManager对象FragmentManager fragmentManager = getFragmentManager();// 开启一个事务FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();// Fragment操作switch (v.getId()) {case R.id.add_btn:// 向容器内加入Fragmentif (!mSecondFragment.isAdded()) {fragmentTransaction.add(R.id.fragment_container1, mSecondFragment);}if (!mThirdFragment.isAdded()) {fragmentTransaction.add(R.id.fragment_container2, mThirdFragment);}break;case R.id.remove_btn:// 从容器类移除FragmentfragmentTransaction.remove(mSecondFragment);break;case R.id.replace_btn:if (!mSecondFragment.isAdded()) {fragmentTransaction.replace(R.id.fragment_container2, mSecondFragment);}break;default:break;}// 提交事务fragmentTransaction.commit();}
}

主要就是为3个按钮设置监听事件,其中第一个按钮为后2个容器添加Fragment,第二个按钮移除第一个容器的Fragment,第三个按钮将容器2里面的Fragment替换。

运行程序可以看到下图所示界面,首先点击“ADD”按钮,将SecondFragment和ThirdFragment动态添加到相应容器。

然后点击“REMOVE”将SecondFragment移除,可以看到SecondFragment被移除,ThirdFragment的位置上移;再点击“REPLACE”按钮将本来加载了ThirdFragment的第二个容器替换为SecondFragment,可以看到替换效果;最后再点击“REMOVE”重新将SecondFragment移除,可以看到最后只剩下FirstFragment。

通过上面的操作相信你应该简单知道如何添加、移除和替换Fragment了。这里有个值得注意的问题是很多同学分不清add操作和replace操作,接下来继续在上面的案例基础上进行修改验证。

在SecondFragment和ThirdFragment中加入Fragment的生命周期方法,同时加入Logcat日志,然后重新运行程序。首先点击“ADD”按钮,将SecondFragment和ThirdFragment动态添加到相应容器。打开Logcat日志可以看到:

然后点击“REMOVE”将SecondFragment移除,再点击“REPLACE”按钮将本来加载了ThirdFragment的第二个容器替换为SecondFragment。打开Logcat日志可以看到:

从上面的2个日志信息可以论证前面所讲的,replace是首先把containerViewId中所有Fagment删除,然后再add进去当前的Fragment 实例。

今天就先到这里,如果有问题欢迎留言一起探讨,也欢迎加入Android零基础入门技术讨论微信群,共同成长!

如果该系列分享对你有帮助,就动动手指关注、点赞、留言吧,你的互动就是对我最大的鼓励!

此文章版权为微信公众号分享达人秀(ShareExpert)——鑫鱻所有,若需转载请联系作者授权,特此声明!

往期总结回顾:

Android零基础入门第1节:Android的前世今生

Android零基础入门第2节:Android 系统架构和应用组件那些事

Android零基础入门第3节:带你一起来聊一聊Android开发环境

Android零基础入门第4节:正确安装和配置JDK, 高富帅养成第一招

Android零基础入门第5节:善用ADT Bundle, 轻松邂逅女神

Android零基础入门第6节:配置优化SDK Manager, 正式约会女神

Android零基础入门第7节:搞定Android模拟器,开启甜蜜之旅

Android零基础入门第8节:HelloWorld,我的第一趟旅程出发点

Android零基础入门第9节:Android应用实战,不懂代码也可以开发

Android零基础入门第10节:开发IDE大升级,终于迎来了Android Studio

Android零基础入门第11节:简单几步带你飞,运行Android Studio工程

Android零基础入门第12节:熟悉Android Studio界面,开始装逼卖萌

Android零基础入门第13节:Android Studio个性化配置,打造开发利器

Android零基础入门第14节:使用高速Genymotion,跨入火箭时代

Android零基础入门第15节:掌握Android Studio项目结构,扬帆起航

Android零基础入门第16节:Android用户界面开发概述

Android零基础入门第17节:文本框TextView

Android零基础入门第18节:输入框EditText

Android零基础入门第19节:按钮Button

Android零基础入门第20节:复选框CheckBox和单选按钮RadioButton

Android零基础入门第21节:开关组件ToggleButton和Switch

Android零基础入门第22节:图像视图ImageView

Android零基础入门第23节:图像按钮ImageButton和缩放按钮ZoomButton

Android零基础入门第24节:自定义View简单使用,打造属于你的控件

Android零基础入门第25节:简单且最常用的LinearLayout线性布局

Android零基础入门第26节:两种对齐方式,layout_gravity和gravity大不同

Android零基础入门第27节:正确使用padding和margin

Android零基础入门第28节:轻松掌握RelativeLayout相对布局

Android零基础入门第29节:善用TableLayout表格布局

Android零基础入门第30节:两分钟掌握FrameLayout帧布局

Android零基础入门第31节:少用的AbsoluteLayout绝对布局

Android零基础入门第32节:新推出的GridLayout网格布局

Android零基础入门第33节:Android事件处理概述

Android零基础入门第34节:Android中基于监听的事件处理

Android零基础入门第35节:Android中基于回调的事件处理

Android零基础入门第36节:Android系统事件的处理

Android零基础入门第37节:初识ListView

Android零基础入门第38节:初识Adapter

Android零基础入门第39节:ListActivity和自定义列表项

Android零基础入门第40节:自定义ArrayAdapter

Android零基础入门第41节:使用SimpleAdapter

Android零基础入门第42节:自定义BaseAdapter

Android零基础入门第43节:ListView优化和列表首尾使用

Android零基础入门第44节:ListView数据动态更新

Android零基础入门第45节:网格视图GridView

Android零基础入门第46节:列表选项框Spinner

Android零基础入门第47节:自动完成文本框AutoCompleteTextView

Android零基础入门第48节:可折叠列表ExpandableListView

Android零基础入门第49节:AdapterViewFlipper图片轮播

Android零基础入门第50节:StackView卡片堆叠

Android零基础入门第51节:进度条ProgressBar

Android零基础入门第52节:自定义ProgressBar炫酷进度条

Android零基础入门第53节:拖动条SeekBar和星级评分条RatingBar

Android零基础入门第54节:视图切换组件ViewSwitcher

Android零基础入门第55节:ImageSwitcher和TextSwitcher

Android零基础入门第56节:翻转视图ViewFlipper

Android零基础入门第57节:DatePicker和TimePicker选择器

Android零基础入门第58节:数值选择器NumberPicker

Android零基础入门第59节:常用三大Clock时钟组件

Android零基础入门第60节:日历视图CalendarView和定时器Chronometer

Android零基础入门第61节:滚动视图ScrollView

Android零基础入门第62节:搜索框组件SearchView

Android零基础入门第63节:值得借鉴学习的选项卡TabHost

Android零基础入门第64节:揭开RecyclerView庐山真面目

Android零基础入门第65节:RecyclerView分割线开发技巧

Android零基础入门第66节:RecyclerView点击事件处理

Android零基础入门第67节:RecyclerView数据动态更新

Android零基础入门第68节:RecyclerView添加首尾视图

Android零基础入门第69节:ViewPager快速实现引导页

Android零基础入门第70节:ViewPager打造TabHost效果

Android零基础入门第71节:CardView简单实现卡片式布局

Android零基础入门第72节:SwipeRefreshLayout下拉刷新

Android零基础入门第73节:Activity创建和配置

Android零基础入门第74节:Activity启动和关闭

Android零基础入门第75节:Activity状态和生命周期

Android零基础入门第76节:Activity数据保存和横竖屏切换

Android零基础入门第77节:Activity任务栈和启动模式

Android零基础入门第78节:四大组件的纽带——Intent

Android零基础入门第79节:Intent 属性详解(上)

Android零基础入门第80节:Intent 属性详解(下)

Android零基础入门第81节:Activity数据传递

Android零基础入门第82节:Activity数据回传

Android零基础入门第83节:Activity间数据传递方法汇总

Android零基础入门第84节:引入Fragment原来是这么回事

Android零基础入门第85节:Fragment使用起来如此简单

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

转载于:https://my.oschina.net/u/3598984/blog/1568111

Android零基础入门第87节:Fragment添加、删除、替换相关推荐

  1. Android零基础入门第89节:Fragment回退栈及弹出方法

    2019独角兽企业重金招聘Python工程师标准>>> 在上一期分享的文章末尾留了一个课后作业,有去思考如何解决吗?如果已经会了那么恭喜你,如果还不会也没关系,本期一起来学习. 一. ...

  2. Android零基础入门第85节:Fragment使用起来非常简单

    2019独角兽企业重金招聘Python工程师标准>>> Fragment创建完成后并不能单独使用,还需要将Fragment加载到Activity中,在Activity中添加Fragm ...

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

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

  4. Android零基础入门第11节:简单几步带你飞,运行Android Studio工程

    2019独角兽企业重金招聘Python工程师标准>>> 之前讲过Eclipse环境下的Android虚拟设备的创建和使用,现在既然升级了Android Studio开发工具,那么对应 ...

  5. Android零基础入门第30节:两分钟掌握FrameLayout帧布局

    原文:Android零基础入门第30节:两分钟掌握FrameLayout帧布局 前面学习了线性布局.相对布局.表格布局,那么本期来学习第四种布局--FrameLayout帧布局. 一.认识FrameL ...

  6. Android零基础入门第25节:最简单最常用的LinearLayout线性布局

    原文:Android零基础入门第25节:最简单最常用的LinearLayout线性布局 良好的布局设计对于UI界面至关重要,在前面也简单介绍过,目前Android中的布局主要有6种,创建的布局文件默认 ...

  7. Android零基础入门第44节:ListView数据动态更新

    2019独角兽企业重金招聘Python工程师标准>>> 经过前面几期的学习,关于ListView的一些基本用法大概学的差不多了,但是你可能发现了,所有ListView里面要填充的数据 ...

  8. Android零基础入门第38节:初识Adapter

    2019独角兽企业重金招聘Python工程师标准>>> 在上一节一起了解了ListView的简单使用,那么本节继续来学习与ListView有着千丝万缕的Adapter. 一.了解MV ...

  9. Android零基础入门第77节:Activity任务栈和启动模式

    2019独角兽企业重金招聘Python工程师标准>>> 通过前面的学习,Activity的基本使用都已掌握,接下来一起来学习更高级的一些内容. Android采用任务栈(Task)的 ...

最新文章

  1. 习题7-1 选择法排序 (20 分)
  2. 屏幕显示密度dpi_PPI和DPI有什么区别?
  3. Celery--分布式任务队列
  4. LINUX怎么修改IP地址
  5. 卷积神经网络(CNN)在无人驾驶中的应用
  6. ORACLE数据库自动备份压缩的批处理脚本 rar 7z
  7. 大数据面试-04-大数据工程师面试题
  8. 什么是线程单线程和多线程_什么是多线程?看我多线程七十二变,你能记住吗?...
  9. SpringBoot常用注解以及作用
  10. html留言板代码_接口测试平台代码实现19.首页优化
  11. 机器学习(二)——xgboost(实战篇)Pima印第安人数据集上的机器学习-分类算法(根据诊断措施预测糖尿病的发病)
  12. mac系统历史版本汇总_苹果发布会 WWDC20 主要更新汇总
  13. 泰坦尼克 数据集_Kaggle-泰坦尼克-学习心得(高分容易,理解很难)——第1篇...
  14. Win7 系统 屏幕旋转快捷键取消(有可能和别的软件有冲突)
  15. WLAN RTT (IEEE 802.11mc)
  16. bzoj 2827 千山鸟飞绝 平衡树
  17. 不同性能测试工具的并发模式
  18. 涉及数字的英语表示——几点钟、年月日、世纪、年代、年龄
  19. NameError: name 'XX' is not defined
  20. 【人工智能】人工智能学习常用社区

热门文章

  1. 使用Kibana画图展示Nginx日志报表
  2. Ubuntu中DenyHosts清除黑名单IP地址
  3. 【Python】ix,loc,iloc的区别
  4. Kali linux 2016.2(Rolling)之 Nessus安装及Plugins Download Fail 解决方法
  5. Java自定义异常、全局捕获异常、拦截器 实现动态控制登录超时
  6. WebSocket 解决javascript跨域问题一剂良药
  7. pytorch神经网络解决回归问题(非常易懂)
  8. getOutputStream() has already been called for this response解释以及解决方法
  9. 尝试安装pg gem时找不到#39;libpq-fe.h标头
  10. win11很卡怎么办 windows11很卡的解决方法