Android基础——Fragment控制切换多个页面

来源:互联网 发布:yum install mysql 编辑:程序博客网 时间:2024/05/02 03:10

A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. 

fragment必须一直嵌入到activity中,并且它的生命周期受activity的影响

For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments

举个列子,当activity暂停,所有的fragments 也是

 However, while an activity is running (it is in the resumed lifecycle state), you can manipulate each fragment independently, such as add or remove them

你可以单独操纵每个片段,如添加或删除它们

When you perform such a fragment transaction, you can also add it to a back stack

当你执行一个事物,你可以添加它到返回栈

 that's managed by the activity—each back stack entry in the activity is a record of the fragment transaction that occurred.

记录发生的事物




1、管理Fragment

要在activity中管理fragment,需要使用FragmentManager. 通过调用activity的getFragmentManager()取得它的实例.

  • 可以通过FragmentManager做一些事情, 包括: 使用findFragmentById()(用于在activity layout中提供一个UI的fragment)或findFragmentByTag()(适用于有或没有UI的fragment)获取activity中存在的fragment。
  • 将fragment从后台堆栈中弹出, 使用 popBackStack() (模拟用户按下BACK 命令)。
  • 使用addOnBackStackChangeListener()注册一个监听后台堆栈变化的listener。

 

2、处理Fragment事务

  关于在activity中使用fragment的很强的一个特性是:根据用户的交互情况,对fragment进行添加、移除、替换以及执行其他动作。提交给activity的每一套变化被称为一个事务,可以使用在FragmentTransaction中的 API 处理。我们也可以保存每一个事务到一个activity管理的backstack,允许用户经由fragment的变化往回导航(类似于通过 activity往后导航)。

从 FragmentManager 获得一个FragmentTransaction实例:

FragmentManager fragmentManager =getFragmentManager();FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();

  每一个事务都是同时要执行的一套变化。可以在一个给定的事务中设置你想执行的所有变化,使用诸如 add()、remove()和 replace()。然后, 要给activity应用事务,必须调用 commit()。
  在调用commit()之前,你可能想调用 addToBackStack(),将事务添加到一个fragment事务的backstack。这个back stack由activity管理, 并允许用户通过按下 BACK按键返回到前一个fragment状态。

http://www.cnblogs.com/mythou/p/3222022.html

0 0
原创粉丝点击