Activity必定要繼承FragmentActivity;一樣是使用android-support-v4.jar包; java
對fragment實例化: MyFragment1 f1 = new MyFragment1();android
取得Manager: FragmentManager manager = getSupportFragmentManager();app
只要對fragment操做,就必須開啓事務: FragmentTransaction transaction = manager.beginTransaction();ide
添加提交: transaction.add(R.id.ll_main_container,f1).commit(); //R.id.ll_main_container 爲佈局文件中的容器佈局
將當前操做加入回退棧,這樣點擊back回到上一個界面: transaction.addToBackStack(null);xml
替換並提交: transaction.replace(R.id.ll_main_container,f2).commit();對象
移除並提交:transaction.remove(f2).commit();blog
主佈局:繼承
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="showFragment2" android:text="顯示Fragment2" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="deleteFragment2" android:text="移除Fragment2" /> </LinearLayout> <LinearLayout android:id="@+id/layout_container" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" /> </LinearLayout>
主Activity:事務
package com.example.fragementdemo; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class MainActivity extends FragmentActivity { //1:建立Fragment對象 //2:添加Fragment對象 private MyFragment1 fragment1; private MyFragment2 fragment2 ; private FragmentManager manager; private FragmentTransaction transaction; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //首先顯示fragment1 fragment1 = new MyFragment1(); //實例化 fragment2 = new MyFragment2(); manager = getSupportFragmentManager(); transaction = manager.beginTransaction(); //開啓事務 transaction.add(R.id.layout_container, fragment1); //添加 transaction.commit(); //提交 } /** * 顯示Fragment2 * @param view */ public void showFragment2(View view ){ transaction = manager.beginTransaction(); //將當前操做加入回退棧,這樣點擊back回到上一個界面 transaction.addToBackStack(null); transaction.replace(R.id.layout_container, fragment2); //替換顯示並提交 transaction.commit(); } /** *移除Fragment2 * @param view */ public void deleteFragment2(View view){ transaction = manager.beginTransaction(); transaction.remove(fragment2).commit(); //移除並提交 } }