Activity一定要继承FragmentActivity;同样是使用android-support-v4.jar包;
对fragment实例化: MyFragment1 f1 = new MyFragment1();
取得Manager: FragmentManager manager = getSupportFragmentManager();
只要对fragment操作,就必须开启事务: FragmentTransaction transaction = manager.beginTransaction();
添加提交: transaction.add(R.id.ll_main_container,f1).commit(); //R.id.ll_main_container 为布局文件中的容器
将当前操作加入回退栈,这样点击back回到上一个界面: transaction.addToBackStack(null);
替换并提交: transaction.replace(R.id.ll_main_container,f2).commit();
移除并提交:transaction.remove(f2).commit();
主布局:
<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(); //移除并提交 } }
原文:http://www.cnblogs.com/suliang-com/p/6390150.html