即:android FragmentTransaction.replace的用法介绍

  Fragment的生命周期和它的宿主Activity密切相关,几乎和宿主Activity的生命周期一致,他们之间最大的不同在于Activity可以增加或删除Fragment。

  

使用FragmentTransaction

  FragmentTransaction可以在运行时添加,删除或替换Fragment,从而实现UI的动态变化。Fragment Transaction由Fragment Manager的beginTransaction()方法创建,然后可以进行Fragment的添加,删除和替换,最后通过commit()方法提交修改。

添加,删除和替换Fragment

  使用FragmentTransaction的add方法可以添加一个新的Fragment,add()方法的主要参数是Fragment的容器View(或其ID)及Fragment实例。

  删除Fragment需要FragmentTransaction的remove()方法,参数为Fragment对象,Fragment对象可以通过FragmentManager的findFragmentById()方法获得。

  替换Fragment使用的是FragmentTransaction的replace()方法,参数分别为所要替代Fragment所在容器的ID和新的Fragment。

获取指定的Fragment

有两种方法可以获取某个特定的Fragment,如果这个Fragment已经被添加到某个layout文件中,则可以使用xml文件中的id作为参数:

[java] view plaincopyprint?

  1. MyFragment myFragment = (MyFragment)fragmentManager.findFragmentById(R.id.MyFragment);

也可以通过创建Fragment时添加的tag获取特定的Fragment:

[java] view plaincopyprint?

    1. MyFragment myFragment = (MyFragment)fragmentManager.findFragmentByTag(MY_FRAGMENT_TAG);

删除Fragment容器

在配置文件中将visibility的属性设为"gone",即可删除某个Fragment

Fragment和Back Stack

Activity拥有Activity Stack,从而在用户按”返回”按钮时,回到前一个Activity。Fragment也可以响应”返回”事件,方法是FragmentTransaction在commit之前调用addToBackStack()方法。这样,在用户按返回键后,Android会首先重现之前的UI布局。

原理和Activity类似,调用addToBackStack()后,Fragment会被push到back stack中,而不是销毁。

Fragment Transaction的动画效果

Fragment Transaction有两种方法实现动画效果,分别是:

  • 设置渐进:

transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

  • 设置动画效果:

[java] view plaincopyprint?

  1. fragmentTransaction.setCustomAnimations(R.animator.slide_in_left, R.animator.slide_out_right);

Fragment和宿主Activity之间的接口

Fragment可以通过getActivity()方法获得宿主Activity对象:

[java] view plaincopyprint?

  1. TextView textView = (TextView)getActivity().findViewById(R.id.textview);

另一种常见的Fragment和Activity之间的交互方式是使用回调函数:

[java] view plaincopyprint?

  1. <span style="font-size:12px">public interface OnSeasonSelectedListener {
  2.   public void onSeasonSelected(Season season);
  3. }
  4. private OnSeasonSelectedListener onSeasonSelectedListener;
  5.   private Season currentSeason;
  6.   @Override
  7.   public void onAttach(Activity activity) {
  8.   super.onAttach(activity);
  9.   try {
  10.   onSeasonSelectedListener = (OnSeasonSelectedListener)activity;
  11.   } catch (ClassCastException e) {
  12.   throw new ClassCastException(activity.toString() +"must implement OnSeasonSelectedListener");
  13.   }
  14.   }
  15.   private void setSeason(Season season) {
  16.   currentSeason = season;
  17.   onSeasonSelectedListener.onSeasonSelected(season);
  18. }</span>

没有UI的Fragment

尽管不常见,但Fragment的确是可以没有UI的,好处也许是拥有了更灵活的生命周期控制。没有UI的Fragment生命周期事件有这些:[java] view plaincopyprint?

  1. public class NewItemFragment extends Fragment {
  2.   @Override
  3.   public void onAttach(Activity activity) {
  4.   <span style="white-space:pre">    </span>super.onAttach(activity);
  5.  <span style="white-space:pre"> </span>// Get a type-safe reference to the parent Activity.
  6.   }
  7.   @Override
  8. public void onCreate(Bundle savedInstanceState) {
  9. <span style="white-space:pre">  </span>  super.onCreate(savedInstanceState);
  10. <span style="white-space:pre">  </span>  // Create background worker threads and tasks.
  11.   }
  12.   @Override
  13.   public void onActivityCreated(Bundle savedInstanceState) {
  14. <span style="white-space:pre">  </span>  super.onActivityCreated(savedInstanceState);
  15. <span style="white-space:pre">  </span>  // Initiate worker threads and tasks.
  16.   }
  17. }

常用的Fragment类

    • DiagFragment
    • ListFragment
    • webViewFragment

下面小例子关于这一用法的介绍:

 thisManager.beginTransaction()
.replace(R.id.tab_container,
new PolicyAssociationCardInfo(framework_))
.addToBackStack("TAG").commit();
package com.bokeyuan.tai.components.PolicyAssociation;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener; import com.bokeyuan.tai.R;
import com.bokeyuan.tai.framework.BaseFragmentActivity; /**
* 保单关联
* @author
*
*/
public class PolicyAssociationActivity extends BaseFragmentActivity {
private static final String TAG = "PolicyAssociationActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
thisManager
.beginTransaction()
.replace(R.id.tab_container,
new PolicyAssociationCardInfo(framework_))
.addToBackStack("TAG").commit();
} catch (Exception e) {
// TODO: handle exception
} } @Override
protected void onStart() {
super.onStart();
topBarObject.topViewMoreButton.setVisibility(View.INVISIBLE); // 标题栏返回
topBarObject.topViewBackButton
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (thisManager.getBackStackEntryCount() <= 1) {
context.finish();
} else {
thisManager.popBackStackImmediate();
} }
});
} }

另外:FragmentTransaction add 和 replace 区别

  使用 FragmentTransaction 的时候,它提供了这样两个方法,一个 add , 一个 replace .

add 和 replace 影响的只是界面,而控制回退的,是事务。

  public abstract FragmentTransaction add (int containerViewId, Fragment fragment, String tag)

Add a fragment to the activity state. This fragment may optionally also have its view (if Fragment.onCreateView returns non-null) into a container view of the activity.

  add 是把一个fragment添加到一个容器 container 里。

public abstract FragmentTransaction replace (int containerViewId, Fragment fragment, String tag)

Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.

  replace 是先remove掉相同id的所有fragment,然后在add当前的这个fragment。是替换页面的意思!

  在大部分情况下,这两个的表现基本相同。因为,一般,咱们会使用一个FrameLayout来当容器,而每个Fragment被add 或者 replace 到这个FrameLayout的时候,都是显示在最上层的。所以你看到的界面都是一样的。但是, 使用add的情况下,这个FrameLayout其实有2层,多层肯定要比一层的来得浪费,所以还是推荐使用replace。 当然有时候还是需要使用add的。比如要实现轮播图的效果,每个轮播图都是一个独立的Fragment,而他的容器FrameLayout需要add多个Fragment,这样他就可以根据提供的逻辑进行轮播了。

而至于返回键的时候,这个跟事务有关,跟使用add还是replace没有任何关系。

下面网上搜得一些理解:
android FragmentTransaction.replace的用法介绍
http://www.07net01.com/2015/04/824163.html Android FragmentManage FragmentTransaction介绍
http://blog.csdn.net/xyz_lmn/article/details/6927763 Android 管理Fragments
http://www.cnblogs.com/mengdd/archive/2013/01/09/2853254.html

最新文章

  1. app引导页(背景图片切换加各个页面动画效果)
  2. iOS多线程同步锁
  3. ajaxfileupload.js支持多文件上传【转载】
  4. 20+功能强大的jQuery/CSS3图片特效插件
  5. Android下实现win8的按钮点击效果
  6. yum update Transaction Check Error
  7. js中Math()函数&amp;&amp;数据类型转换
  8. 理解 PHP 中的 Streams
  9. nvmw install 失败. 需修改&quot;Msxml2.XMLHTTP&quot;为&quot;Msxml2.ServerXMLHTTP&quot;
  10. CentOS6.5 x86_64 配置Broadcom 43XX系列 无线网卡驱动
  11. IDEA的热部署插件jrebel6.4.3版离线安装版配置与破解
  12. Python3_打开和运行方式
  13. Web API &lt;五&gt; 序列化
  14. HDP2.0.6+hadoop2.2.0+eclipse(windows和linux下)调试环境搭建
  15. SqlServer2012,设置指定数据库对指定用户开放权限
  16. iisapp -a命令出现 :此脚本不能与WScript工作
  17. 默认以管理员身份运行VS2013/15/17
  18. java压缩流
  19. PyQt5信号与槽
  20. MarkdownPad 2.x破解下载

热门文章

  1. vs2010 rdlc .net4.0 卸载 Appdomain 时出错。 (异常来自 HRESULT:0x80131015) 解决办法
  2. php读取csv文件,在linux上出现中文读取不到的情况 解决方法
  3. POJ 2083 Fractal
  4. JAVA 多线程编程之一(基础)
  5. Base64 算法原理,以及编码、解码【加密、解密】 介绍
  6. 网络拥塞控制与NS2仿真
  7. MySQL单机load过高问题讨论
  8. html5 自定义数据属性 ,也就是 data-* 自定义属性---笔记。
  9. 0406.复利计算器5.0版-release
  10. Spring MVC的web.xml配置详解(转)