Android provides an easy way to switch between actions using TabHost. You can also use it to switch between fragments, as described in the TabActivity section. In addition, you can add FrameLayout to your activities, programmatically instantiate fragments and attach / show / hide them when necessary.
Your res / layout / main.xml will look like this:
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:layout_width="match_parent" android:id="@+id/mainframe"> </FrameLayout>
And if you are supposed to use the v4 support library, your activity will look like this:
public MyActivity extends FragmentActivity { private Fragment mListFrag; private Fragment mGameFrag; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mListFrag = new MyListFragment(); mGameFrag = new MyGameFragment(); FragmentManager fm = getSupportFragmentManager(); fm.beginTransaction() .add( R.id.mainframe, mListFrag, MyListFragment.class.getName()) .add( R.id.mainframe, mGameFrag, MyGameFragment.class.getName()) .detach(mGameFrag) .commit(); fm.executePendingTransactions(); } public void showList() { getSupportFragmentManager().beginTransaction() .hide(mGameFrag) .show(mListFrag) .commit(); } public void showGame() { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); if (mGameFrag.isDetached()) { ft.attach(mGameFrag); } ft.hide(mListFrag).show(mGameFrag).commit(); } }
Note that MyGameFragment.onCreateView is not called until it is attached first. After that, hiding and displaying fragments allows the user to switch without delay.
Edit: I now understand that you need 2 actions with your button. I updated the code to reflect this. From OnClickListeners, just call the corresponding activity functions as follows:
((MyActivity) MyListFragment.this.getActivity()).showGame();
user999717
source share