您的位置:首页 > 移动开发 > Android开发

Android Fragment 替换覆盖生命周期方法详解

2016-03-14 21:26 239 查看

FragMent add 与 replace 方法执行试图切换生命周期变化

Activity 生命周期中共有七个方法,Fragment 的生命周期方法 则有11个,一个Fragment 在Activity中生命周期对比 ,网上很多文章都是,在这就不说了

当两个fragment 之间切换时,生命周期方法又是如何调用的呢

在此做个实验,分别创建两个碎片,内涵11个生命周期方法,syso打印(本人比较喜欢syso)

`package com.example.fragmentlife;

import android.app.Activity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import frag1.Frag1;

import frag1.Frag2;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//初始化布局 加载 ListFragment 使用replace 方法替换布局
try {
initView();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* @Title:        initView
* @Description:  TODO(这里用一句话描述这个方法的作用)
* @param:
* @return:       void
* @throws InterruptedException
* @throws
* @author        Designed By Ly
* @Date          2016年3月14日 下午8:58:43
*/
private void initView() throws InterruptedException {

getFragmentManager().beginTransaction()
.add(R.id.frame, new Frag1()).commit();


// getFragmentManager().beginTransaction()

// .replace(R.id.frame, new Frag2()).commit();

Thread.sleep(300);

getFragmentManager().beginTransaction()
.add(R.id.frame, new Frag2()).commit();

}


}

`

- 先将 fg1 添加入 activity 布局中 再使用add 方法 将 fg2 加入布局,观察程序运行结果如下:

-


使用replace 结果如下

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: