Fragment不能獨立存在,它必須嵌入到activity中,而且Fragment的生命周期直接受所在的activity的影響。例如:當activity暫停時,它擁有的所有的Fragment們都暫停了,當activity銷毀時,它擁有的所有Fragment們都被銷毀。
此文章沒有任何講解,只是純粹的代碼文檔,列舉幾種方法,忘記的時候方便查看鞏固使用的。
方法一:
在activity的layoutxml文件中聲明fragment**
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false">
<fragment
android:id="@+id/titles"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="4"
class="cn.eoe.first.fragment.LeftFragment"/>
<fragment
android:id="@+id/details"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
class="cn.eoe.first.fragment.RightFragment"/>
</LinearLayout>
class= "cn.eoe.first.fragment.LeftFragment" 換成
android:name="cn.eoe.first.fragment.LeftFragment"也可以
方法二:在代碼中添加fragment到一個ViewGroup**
//先獲得Fragment的管理
FragmentManager fragmentManager = getFragmentManager();
//所有Fragment的事務都是通過FragmentTransaction來完成,在通過管理者獲取事務對象
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
//實例化要添加的Fragment
MyFragment fragment = new MyFragment();
//添加Fragment通過layout中的id,實例對象,還有tag標簽
fragmentTransaction.add(R.id.fragment_container1, fragment,"fragment");
//提交
fragmentTransaction.commit();
或者
FragmentTransaction tx =getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main, Fragment.instantiate(MyHomeSlidingActivity.**this**,
"com.joymis.audio.FragmentmyhomeInfo"));
tx.commit();
其中 "com.joymis.audio.FragmentmyhomeInfo"的代碼
public class FragmentmyhomeInfo extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_myhome_fragment, container,**false**);
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
}
layout中的布局為
<FrameLayout
android:id="@+id/fragment_container1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
其他
要管理fragment們,需使用FragmentManager,要獲取它,需在activity中調用方法getFragmentManager()。
你可以用FragmentManager來做以上事情:
1使用方法findFragmentById()或findFragmentByTag(),獲取activity中已存在的fragment們。
2使用方法popBackStack()從activity的后退棧中彈出fragment們(這可以模擬后退鍵引發的動作)。
3用方法addOnBackStackChangedListerner()注冊一個偵聽器以監視后退棧的變化。