Fragment 好久没用了,再不复习下就忘了,本篇来总结一下Fragment 常用方法以及注意点。
一、Fragment 生命周期
onAttach - onCreate - onCreateView - onActivityCreated - onStart - onResume - onPause - onStop - onDestoryView - onDestory - onDetach官网的生命周期图:
onAttach : onAttach()在fragment与Activity关联之后调
onCreate : fragment初次创建时调用
onCreateView : 创建Fragment的视图
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment3, container, false);
}
参数:
1. 布局文件
2. container: 指父窗口
onActivityCreated : 在一个Activity中第一次创建Fragment的时候,在onActivityCreated之前的方法虽然可以获得getActivity实例,但是没法获得其他fragment中的控件
getActivity().findViewById(R.id.frag_text_two) 为null; 之后创建的fragment 从onAttach开始就能获得实例; 在这个函数中才可以使用Activity的所有资源
onStart : 部分视图已经出现,但是无焦点,用户无法与Fragment交互; 与Activity中的onStart 意义一样
onResume : fragment已经完全可见,并且用户可以对Fragment进行操作
下面几个方法都是依赖Activity的生命周期
onPause : 此回调与Activity的OnPause()相绑定,与Activity的OnPause()意义一样。
onStop : 这个回调与Activity的OnStop()相绑定,意义一样。已停止的Fragment可以直接返回到OnStart()回调,然后调用OnResume()。
onDestroyView : 会将在onCreateView创建的视图与这个fragment分离
onDestory : 当这个fragment不再使用时调用。需要注意的是,它即使经过了onDestroy()阶段,但仍然能从Activity中找到,因为它还没有Detach。
onDeatch : 该Fragment 将被释放, 不再与Activity绑定
二、创建Fragment
1. 静态创建
fragment 其实就是一个控件,可以在xml中直接使用,通过name来确认需要加载的Fragment类效果图如下:
步骤:
(1) 自定义FragmentFirst extends Fragment,并重写方法onCreateView
public class FragmentFirst extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Log.d("stormxz", "FragmentFirst onCreateView " + getActivity().findViewById(R.id.frag_text_two));
return inflater.inflate(R.layout.fragment_first, container, false);
}
}
FragmentFirst layout 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="@color/colorFragmentFi">
<TextView
android:id="@+id/frag_text_two"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/first_fragment"/>
</LinearLayout>
layout如下:
注意点:
(1)id必须加上,否则会报; 根据抛出的异常,可以看到给fragment父类加上id,此时是不会报错的; 已测验通过。
Caused by: java.lang.IllegalArgumentException: Binary XML file line #18: Must specify unique android:id, android:tag, or have a parent with an id for com.example.stormxz.fragmentdemo.FragmentTwo
(2)name 属性用来确定该fragment使用自定义的哪个Fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.stormxz.fragmentdemo.MainActivity">
<!--静态注册fragment id 必须填写-->
<fragment
android:id="@+id/fragmentfirst"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:name="com.example.stormxz.fragmentdemo.FragmentFirst"/>
<fragment
android:id="@+id/fragmentsecond"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:name="com.example.stormxz.fragmentdemo.FragmentTwo"/>
</LinearLayout>
2. 动态创建
动态注册主要体现在Activity 中, 比如点击一个button ,创建FragmentFirst
获得Fragment管理器
FragmentManager manager = getSupportFragmentManager();
开启事务
FragmentTransaction fragmentTransaction = manager.beginTransaction();
创建需要添加的Fragment对象
FragmentFirst fragmentFirst = new FragmentFirst();
将fragment添加到容器id为frame的布局中,并且设置tag为first
fragmentTransaction.add(R.id.frame, fragmentFirst, "first");
提交事务
fragmentTransaction.commit();
(1)FragmentManager 属于Fragment 的管理类
常用方法beginTransaction(); //获得FragmentTransaction
findFragmentById(int id); //通过id 获得fragment对象
findFragmentByTag("string"); //通过tag获得对应的fragment对象
getFragments(); //获得所有被事务add进的fragments
(2)FragmentTransaction 事务,对Fragment进行添加,移除,替换等操作
代码:将上方的add进行更改//将一个fragment实例添加到Activity的最上层
add(int containerViewId, Fragment fragment, String tag);
//将一个fragment实例从Activity的fragment队列中删除
remove(Fragment fragment);
//替换containerViewId中的fragment实例,注意,它首先把containerViewId中所有fragment删除,然后再add进去当前的fragment
replace(int containerViewId, Fragment fragment);
三、FragmentTransaction 回滚 将上一次commit回退
注: 回滚,以commit为单位; 只addToBackStack一个时,回滚会不生效,所以在回退栈中必须大于1个才能进行回退步骤:
(1)在fragmentTransaction.commit() 之前
fragmentTransaction.addToBackStack("TAG");
(2)回滚操作
manager.popBackStack(); //默认回滚栈顶的内容
manager.popBackStack(int id, int flag);
manager.popBackStack(String tag, int flag);
参数int id是当提交变更时在fragmentTransaction.commit()的返回值。
参数string name是在fragmentTransaction.addToBackStack(String tag)中的tag值;
参数flag:
0: 回退到addToBackStack的
FragmentManager.POP_BACK_STACK_INCLUSIVE: 连同addToBackStack的一起回退
使用popBackStack()来弹出栈内容的话,调用该方法后会将事物操作插入到FragmentManager的操作队列,只有当轮询到该事物时才能执行。如果想立即执行事物的话,需要使用下面几个对应的方法:
popBackStackImmediate()
popBackStackImmediate(String tag)
popBackStackImmediate(String tag, int flag)
popBackStackImmediate(int id, int flag)
(3)监听backStack
FragmentManager.OnBackStackChangedListener listener = null;
FragmentManager fmanager = getSupportFragmentManager();
listener = new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
Log.d("stormxz", "onBackStackChanged ");
}
};
fmanager.addOnBackStackChangedListener(listener);
记得不使用时,移除监听
fmanager.removeOnBackStackChangedListener(listener);
四、hide()、show()、detach()、attach()
1. hide(), show() 仅仅是隐藏和显示,对其生命周期不再重新创建
FragmentTransaction hide(Fragment mFragment) //将指定的fragment隐藏 如果在当前界面,则现实下一个FragmentFragmentTransaction show(Fragment mFragment) //将以前hide()过的fragment显示
private void hideFragment(String tag) {
FragmentManager fmanager = getSupportFragmentManager();
Fragment fr = fmanager.findFragmentByTag("thr");
FragmentTransaction ftransaction = fmanager.beginTransaction();
ftransaction.hide(fr);
ftransaction.commit();
}
在项目中的正常使用方式:
public void switchContent(Fragment from, Fragment to) {
if (!to.isAdded()) { // 先判断是否被add过
transaction.hide(from).add(R.id.content_frame, to).commit(); // 隐藏当前的fragment,add下一个到Activity中
} else {
transaction.hide(from).show(to).commit(); // 隐藏当前的fragment,显示下一个
}
}
2. detach(), attach()
detach() 一方面删除fragment的View视图;一方面将fragment从Activity的ADD队列中移除attach() 删除之前那个,重新创建了一个fragment, 并加入栈顶
五、打出回退栈中的内容(通过FragmentTransaction.addToBackStack)
public int getBackStackEntryCount();//获取回退栈中,Transaction回退操作的数量public BackStackEntry getBackStackEntryAt(int index);//根据索引得到回退栈变量
TextView tv = (TextView) findViewById(R.id.tv_stack_val);
FragmentManager manager = getSupportFragmentManager();
int count = manager.getBackStackEntryCount();
StringBuilder builder = new StringBuilder("回退栈内容为:\n");
for (int i = --count;i>=0;i--){
FragmentManager.BackStackEntry entry= manager.getBackStackEntryAt(i);
builder.append(entry.getName()+"\n");
}
tv.setText(builder.toString());
六、关于add 与 replace不能同用问题
for (int i=0;i<mManager.mAdded.size(); i++) {
Fragment old = mManager.mAdded.get(i);
……
mManager.removeFragment(old, mTransition, mTransitionStyle);
}
比如add fragment0,fragment1,fragment2,fragment3, replace fragment4
当调用replace时,看上面方法会移除fragment,在这里就是移除fragment0 1 2 3
但是当i = 0时,移除的是0,剩余 1 2 3 4
当i = 1 时,此时0 为1, 1 为2, 所以剩下1, 3, 4
此时并没有移除干净,所以在返回时会出现问题。
所以建议add与replace别一起用。
七、主模块测试代码
MainActivity: 注意这边使用的是v4 中的Fragment,比系统中的功能更多点
package com.example.stormxz.fragmentdemo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends FragmentActivity implements View.OnClickListener{
private Button firstBu = null;
private Button secondBu = null;
private Button thrBu = null;
private Button fourBu = null;
private Button removeBu = null;
private Button popBackStack_0 = null;
private Button popBackStack_flag = null;
private Button hideBu = null;
private Button showBu = null;
private Button attachBu = null;
private FragmentManager.OnBackStackChangedListener listener = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("stormxz", "MainActivity onCreate");
setContentView(R.layout.activity_main);
init();
FragmentManager fmanger = getSupportFragmentManager();
listener = new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
Log.d("stormxz", "onBackStackChanged ");
}
};
fmanger.addOnBackStackChangedListener(listener);
}
private void init() {
firstBu = findViewById(R.id.first_button);
secondBu = findViewById(R.id.second_button);
thrBu = findViewById(R.id.thr_button);
fourBu = findViewById(R.id.four_button);
removeBu = findViewById(R.id.remove);
popBackStack_0 = findViewById(R.id.popBackStack_0);
popBackStack_flag = findViewById(R.id.popBackStack_flag);
attachBu = findViewById(R.id.attach);
hideBu = findViewById(R.id.hide);
showBu = findViewById(R.id.show);
firstBu.setOnClickListener(this);
secondBu.setOnClickListener(this);
thrBu.setOnClickListener(this);
fourBu.setOnClickListener(this);
removeBu.setOnClickListener(this);
popBackStack_0.setOnClickListener(this);
popBackStack_flag.setOnClickListener(this);
hideBu.setOnClickListener(this);
showBu.setOnClickListener(this);
attachBu.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.first_button:
FragmentFirst fragmentFirst = new FragmentFirst();
addFragment(fragmentFirst, "first", false);
break;
case R.id.second_button:
FragmentTwo ftwo = new FragmentTwo();
addFragment(ftwo, "second", true);
break;
case R.id.thr_button:
Fragment fThr = new FragmentThree();
addFragment(fThr, "thr", false);
break;
case R.id.four_button:
Fragment fFour = new FragmentFour();
addFragment(fFour, "four", false);
break;
case R.id.popBackStack_0:
popBackStack("second", 0);
break;
case R.id.popBackStack_flag:
Log.d("stormxz", "popBackStack_flag");
popBackStack("second", FragmentManager.POP_BACK_STACK_INCLUSIVE);
break;
case R.id.remove:
FragmentManager fm1 = getSupportFragmentManager();
FragmentTransaction ft2 = fm1.beginTransaction();
Fragment fr = fm1.findFragmentByTag("first");
ft2.remove(fr);
ft2.commit();
break;
case R.id.hide:
hideFragment("thr");
break;
case R.id.show:
showFragment("thr");
break;
case R.id.attach:
attach();
break;
}
}
private void showFragment(String tag) {
FragmentManager fmanager = getSupportFragmentManager();
Fragment fr = fmanager.findFragmentByTag("thr");
FragmentTransaction ftransaction = fmanager.beginTransaction();
ftransaction.show(fr);
ftransaction.commit();
}
private void attach(){
FragmentManager manager = getSupportFragmentManager();
Fragment fragment = manager.findFragmentByTag("first");
FragmentTransaction transaction = manager.beginTransaction();
transaction.attach(fragment);
transaction.addToBackStack("first");
transaction.commit();
}
private void hideFragment(String tag) {
FragmentManager fmanager = getSupportFragmentManager();
Fragment fr = fmanager.findFragmentByTag("thr");
FragmentTransaction ftransaction = fmanager.beginTransaction();
ftransaction.hide(fr);
ftransaction.commit();
}
private void addFragment(Fragment mFragment, String tag, boolean pop){
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.add(R.id.frame, mFragment, tag);
if (pop) {
fragmentTransaction.addToBackStack(tag);
} else {
fragmentTransaction.addToBackStack(null);
}
fragmentTransaction.commit();
}
private void popBackStack(String tag, int flag){
FragmentManager manager = getSupportFragmentManager();
manager.popBackStack(tag, flag);
}
@Override
protected void onStart() {
super.onStart();
Log.d("stormxz", "MainActivity onStart");
}
@Override
protected void onResume() {
super.onResume();
Log.d("stormxz", "MainActivity onResume");
}
@Override
protected void onPause() {
super.onPause();
Log.d("stormxz", "MainActivity onPause");
}
@Override
protected void onStop() {
super.onStop();
Log.d("stormxz", "MainActivity onStop");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("stormxz", "MainActivity onDestroy");
FragmentManager fm = getSupportFragmentManager();
fm.removeOnBackStackChangedListener(listener);
}
}