Search This Blog

28 May 2010

Saving State

Building on our Menus example, let's take a look at saving and restoring state.

Let's replace the content of your activity (src\main\java\org\eoti\android\MenuTestActivity.java  in my case):

public class MenuTestActivity extends Activity {
    private static String TAG = "MenuTest";
    private static String CURRENT_MENU_KEY = "CURRENT_MENU_KEY";
    private Menu menu;
    private SharedPreferences prefs;   
    private int current_menu;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        prefs = getPreferences(MODE_PRIVATE);
        changeMenu(prefs.getInt(CURRENT_MENU_KEY, R.id.first));
    }

    @Override
    protected void onPause() {
        super.onPause();
        SharedPreferences.Editor ed = prefs.edit();
        ed.putInt(CURRENT_MENU_KEY, current_menu);
        ed.commit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        changeMenu(prefs.getInt(CURRENT_MENU_KEY, R.id.first));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mainmenu, menu);
        this.menu = menu;
        changeMenu(current_menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return changeMenu(item.getItemId());
    }

    private boolean changeMenu(int id)
    {
        switch (id)
        {
            case R.id.first:
                if(menu != null)
                {
                    menu.setGroupVisible(R.id.first_menu, true);
                    menu.setGroupVisible(R.id.second_menu, false);
                }
                current_menu = id;
                return true;
            case R.id.second:
                if(menu != null)
                {
                    menu.setGroupVisible(R.id.first_menu, false);
                    menu.setGroupVisible(R.id.second_menu, true);
                }
                current_menu = id;
                return true;
        }
        return false;
    }
}

Redeploy (mvn clean install) and launch your app.  Now, when you exit the app (back, home, whatever) and relaunch, it will default to the same menu choice it was on before closing.

No comments:

Post a Comment