生命周期
如果当前Activity正在运行,当Fragment被添加到Activity后,就会依次调用以下生命周期回调:
onAttach():当Fragment首次依附在某个Context时调用。
onCreate():做一些初始化动作,注意这个回调可能在对应Activity的视图层级还在创建的时候调用。
onCreateView():用来初始化Fragment的界面,如果这个Fragment没有界面,直接返回null即可。
onActivityCreated():在对应Activity已经创建以及该Fragment的界面初始化完毕之后调用。
onStart():当Fragment可见的时候调用,通常与对应Activity的onStart()绑定。
onResume():当Fragment对用户可见并且正在运行的时候调用,通常与对应Activity的onResume()绑定。
onPause():当Fragment不处于resumed状态的时候调用,通常与对应Activity的onPause()绑定。
onStop():当Fragment不处于started状态的时候调用,通常与对应Activity的onStop()绑定。
onDestroyView():当onCreateView()返回的View从Fragment上分离出来的时候调用,如果之后Fragment又需要显示,会再去调用onCreateView()。不管onCreateView()有没有返回非空View,总是会回调这个方法。
onDestroy():当不需要再用Fragment的时候调用。
onDetach():当Fragment脱离Activity的时候调用。
与Activity的生命周期相比,Fragment的生命周期整体来看:
首先是一个依附与脱离Activity的过程:onAttach()和onDetach()。
然后是创建与销毁的过程:onCreate()和onDestroy()。
接下来是视图创建的过程:onCreateView()和onDestroyView()。
onCreateView()后有个onActivityCreate()回调。
中间阶段则是类似Activity的onStart()-onResume()-onPause()-onStop()。
转场动画
Fragment自定义转场动画:
mFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.scale_in, R.anim.alpha_out)
.replace(R.id.container, fragment).commit();
缩放进入scale_in
<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="600"
android:fromXScale="1"
android:fromYScale="0"
android:toXScale="1"
android:toYScale="1">
</scale>
淡出alpha_out
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="200"
android:fromAlpha="1"
android:toAlpha="0">
</alpha>