美文网首页
Fragment 笔记

Fragment 笔记

作者: chauI | 来源:发表于2016-11-21 18:28 被阅读25次

简介

碎片、片段,Fragment 的翻译可以让人直观的了解到它设计的思路和用法。
Android 3.0 以上。


出自 [郭霖大神的 CSDN](http://blog.csdn.net/guolin_blog/article/details/8881711)

这时点击一下home键,打印日志如下:

出自 [郭霖大神的 CSDN](http://blog.csdn.net/guolin_blog/article/details/8881711)

如果你再重新进入进入程序,打印日志如下:

出自 [郭霖大神的 CSDN](http://blog.csdn.net/guolin_blog/article/details/8881711)

然后点击back键退出程序,打印日志如下:

出自 [郭霖大神的 CSDN](http://blog.csdn.net/guolin_blog/article/details/8881711)

Fragment 的创建

简单的 Fragment 可以通过重写 onCreateView() 方法来实现。

onCreateView(LayoutInflater inflater, ViewGroup container,BundlesavedInstanceState) 

一般使用该方法返回一个 View 对象提供给 Activity ,
所以在这里加载 xml 布局文件,参数中,
container :参数是布局将插入到的父ViewGroup(来自 Activity 的布局)
savedInstanceState :在恢复 Frafment 时,提供上一片段实例相关数据的 Bundle
inflater : 可以用来获取 xml 文件的控件。

View view = inflater.inflate(R.layout.activity_news_two,container,false);
ListView newslistView=(ListView) view.findViewById(R.id.show_news);
//ListView newslistView = (ListView) getActivity().findViewById(R.id.show_news);
//getActivity() 获取的对象可以用来获取同一个 Activity 上不同的 Fragment 的控件。

inflate 方法的三个参数:
xml 文件的ID;
将作为扩展布局父项的 ViewGroup 对象。传递 container对系统向扩展布局的根视图(由其所属的父视图指定)应用布局参数具有重要意义;
指示是否应该在扩展期间将扩展布局附加至 ViewGroup(第二个参数)的布尔值。

Activity 与 Fragment

  • 动态添加、删除 Fragment

获取 FragmentTransaction 对象

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container,fragment);//添加到的地方
//fragmentTransaction.remove(fragment);
//fragmentTransaction.replace();
//fragmentTransaction.hide();
//fragmentTransaction.show();
fragmentTransaction.commit();
  • 两者的通信
  • 事务栈

调用 addToBackStack(),以将事务添加到片段事务返回栈。 该返回栈由 Activity 管理,允许用户通过按返回按钮返回上一片段状态

transaction.add(R.id.fragment_container,fragment);
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);//

transaction.commit();

点击返回的时候,上面的操作会被全部撤销。
而且这些操作还可以通过setTransition()设置过度动画

setTransition

相关文章

  • Fragment学习笔记(基础篇)

    Fragment学习笔记 一、Fragment的定义 Fragment是在Android 3.0才开始引入的,它能...

  • Fragment使用总结

    title: Fragment使用总结tags: 学习笔记,Android,Fragment 原文:Fragme...

  • fragment

    Android fragment源码全解析 Android源码阅读笔记(1)----Fragment 关于Frag...

  • 笔记:Fragment

    onAttach():执行该方法时,fragment与activity已经完成绑定,该方法有一个Activity类...

  • Fragment笔记

    Fragment 为何产生 同时适配手机和平板、UI和逻辑的共享。 介绍 Fragment也会被加入回退栈中。 F...

  • Fragment 笔记

    常用的一些方法 生命周期 参考 郭霖大神的 CSDN 、Android Developer 简介 碎片、片段,Fr...

  • Fragment笔记

    1、Fragment 的生命周期? Fragment 从创建到销毁整个生命周期中涉及到的方法依次 为:onAtta...

  • Fragment笔记

    定义:即为小型的activity,称为activity片段,他开发之初是为了适用于平板。 生命周期:需要依附于ac...

  • Fragment笔记

    ViewPager正确使用+源码解析:https://baijiahao.baidu.com/s?id=16674...

  • Android Fragment笔记

    生命周期 常用的子类 DialogFragment 显示浮动对话框 ListFragment 显示由Adapter...

网友评论

      本文标题:Fragment 笔记

      本文链接:https://www.haomeiwen.com/subject/awvupttx.html