I would put this code in activity class, that must have FrameLayout with id R.id.fragment_container.
private Fragment1 F1;
private Fragment2 F2;
private Fragment3 F3;
private Fragment4 F4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
F1 = new Fragment1();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, F1).commit();
F2 = new Fragment2();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, F2).commit();
F3 = new Fragment3();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, F3).commit();
F4 = new Fragment4();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, F4).commit();
//if needed show F1
getSupportFragmentManager().beginTransaction().show(F1).commit();
}
And add this for button click:
public void onBtnClick(View view){
if(mShowF1){
getSupportFragmentManager().beginTransaction().show(F1).commit();
getSupportFragmentManager().beginTransaction().hide(F2).commit();
getSupportFragmentManager().beginTransaction().hide(F3).commit();
getSupportFragmentManager().beginTransaction().hide(F4).commit();
}
//...
}
On button click(s) you can show, that fragment that you want and hide others.
NOTE (@developer1011):
For use after activity save state call commitAllowingStateLoss ()
. Use with care, because fragment is not restored with activity restoration.
NOTE:
MainActivity should implement OnFragmentInteractionListener for each Fragment.
public class MainActivity extends FragmentActivity implements Fragment1.OnFragmentInteractionListener, Fragment2.OnFragmentInteractionListener, Fragment3.OnFragmentInteractionListener, Fragment4.OnFragmentInteractionListener {//..
@Override
public void onFragmentInteraction(Uri uri) {
//
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…