1.对父activity附加和分离fragments分别经过onAttach和onDetach android
fragment/activity 到了pause状态,onDetach是有可能不被调用就挂了,由于父activity的进程可能由于资源紧张被杀死。(意外死亡)布局
onAttach通常是用来获取对父activity的引用。(由于你可能须要用到父activity来初始化你的一些东西)动画
2.建立和销毁Fragments ui
与activity同样,你应该使用onCreate方法去初始化你的fragments。(onCreate方法在整个生命周期只执行1次)。spa
注意:不像activity,fragment的ui初始化可不在onCreate方法中,而是onCreateView..net
若是fragment须要与父activtiy的UI交互,那么你须要等onActivityCreate方法触发才能够,由于这个方法意味着你的activity已经完整初始化好了。code
3.Fragment状态 xml
再次强调,fragment的命运与activity是息息相关的。所以,fragment的状态经常要去参考activity的状态,由于要保持一致。blog
当activities获取到焦点,那么它所含的fragments也能获取到焦点。当activity暂停或者中止,fragments也暂停或者中止 。。。。。等等,当activity死掉了,fragment必须死。生命周期
4.Fragment Manager
每一个activity包含一个fragment manager去管理它所包含的fragments. 你能够获取fragment manager经过getFragmentManager方法。
FragmentManager fragmentManager = getFragmentManager()
FragmentManager提供方法去获取和使用Fragments和执行Fragment事务:增长,移除,或者代替Fragments.
1.增长Fragments到Activities
最简单的方式,固然XML喽,直接例子不解释了:(tag或者id是必须给一个的,便于后期查找,也便于activity重启的时候系统用来恢复)
12345678910111213141516171819<LinearLayout xmlns:android=”http:
//schemas.android.com/apk/res/android”
android:orientation=”horizontal”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<fragment android:name=”com.paad.weatherstation.MyListFragment”
android:id=”@+id/my_list_fragment”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_weight=”
1
”
/>
<fragment android:name=”com.paad.weatherstation.DetailsFragment”
android:id=”@+id/details_fragment”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_weight=”
3
”
/>
</LinearLayout>
5.使用Fragment事务:
事务能够用来增长,移除,替换Fragments. 使用事务可使你的布局动态化,能够基于用户的交互和APP的状态作适应和改变。它们还支持指定显示的过渡动画和是否去包含事务在Back Stack。
使用beginTransaction一个新的Fragment事务(FragmentManager的方法)。若是须要,在你设置显示的动画前,可使用add,remove,replace方法修改布局和设置合适的back-stack行为。当你准备好改变的时候,使用commit去提交到UI队列中。
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Add, remove, and/or replace Fragments.
// Specify animations.
// Add to back stack if required.
fragmentTransaction.commit();
增长、移除或者代替Fragments:
add:
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.ui_container, new MyListFragment());
fragmentTransaction.commit();
注意!!!:fragment没视图时,你只能指定tag(add(Fragment fg,String tag)),若是有视图,tag和id均可以。
首先必须明白,既然是动态添加的,我怎么知道该加到布局的哪部分,因此这里要指定父布局容器的ID,R.id.ui_container。
remove:
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = fragmentManager.findFragmentById(R.id.details_fragment);
fragmentTransaction.remove(fragment);
fragmentTransaction.commit();
replace:
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.ui_container, new DetailFragment(selected_index)); //还有个重载方法,能够为新的fragment指定tag fragmentTransaction.commit(); //这里也解释为何无视图的不能有id,没有视图哪来的父容器? 因此也不能findFragmentByID