Avoiding reinitialization of activities that take a long time to initialize

I have an application with two screens and buttons that switch between them. One screen is basically a listView, but the other has a game engine (AndEngine), and it may take a while for the game engine to start to trigger the first time an action is created. Therefore, switching between them can cause great delays when switching to a new Engine game. However, if I just use the back button, the previous game engine loads much faster. Is there a way that I can specify to create only one game engine and always call this instance of activity? Right now I'm using startIntent () to share screens. Is there another way? A way that allows me to have only one instance of each action and change them among themselves?

+1
android
source share
1 answer

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();

+3
source share

All Articles