/**
* 片段可以重叠
* 添加片段
*/
public void add(View view) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment, new RedFragment());
ft.commit();
}
/**
* 删除当前布局上的片段
*/
public void del(View view) {
FragmentManager fm = getSupportFragmentManager();
Fragment currentFragment = fm.findFragmentById(R.id.fragment);
if (currentFragment != null) {
FragmentTransaction ft = fm.beginTransaction();
ft.remove(currentFragment);
ft.commit();
}
}
/**
* 不管之前后没有都会替换掉
*/
public void replace(View view) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment, new BlueFragment());
ft.commit();
}
/**
* 添加到回退栈
*/
public void toBack(View view) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment, new RedFragment());
ft.addToBackStack(null);
ft.commit();
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.zxc.myapplication.MainActivity">
<LinearLayout
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:onClick="add"
android:text="添加"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_add"/>
<Button
android:onClick="del"
android:text="删除"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_del"/>
<Button
android:onClick="replace"
android:text="替换"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_rep"/>
<Button
android:onClick="toBack"
android:text="添加到回退栈"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_toback"/>
</LinearLayout>
<FrameLayout
android:id="@+id/fragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"></FrameLayout>
</LinearLayout>
</RelativeLayout>