R.id.initial_fragment布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include layout="@layout/title_custom"/>
<LinearLayout
android:id="@+id/initial_frament"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
</LinearLayout>
fragment切换函数:
public Fragment currentFragment = null; //方便快速切换
public Fragment mOldFragment = null; //方便back键返回上一个fragment
public void switchFragment(Fragment oldFragment, Fragment newFragment){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if(oldFragment != null)
transaction.hide(oldFragment);
if(!newFragment.isAdded()){
transaction.add(R.id.initial_frament,newFragment);
}
transaction.show(newFragment).commitAllowingStateLoss();
currentFragment = newFragment;
mOldFragment = oldFragment;
}