androidsharedpreferences

Android Menu only works once per app run


I've hit a weird problem with my Android app. My main activity has a menu attached to the menu button. Problem is, the menu button works exactly once. Once pressed, the app has to be restarted before the menu button will work again.

The (sanitised) code is:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.main);

    settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    startActivity(new Intent(this, PreferencesActivity.class));

    return(super.onCreateOptionsMenu(menu));
}

@Override
public void onBackPressed() {
    this.finish();
}

@Override
public void onDestroy() {
    super.onDestroy();
    this.finish();
}

@Override
public void onStop() {
    super.onStop();
    this.finish();
}

and the preferences activity looks like

public class PreferencesActivity extends PreferenceActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

        addPreferencesFromResource(R.xml.preferences);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
        this.finish();
    }

    @Override
    public void onBackPressed() {
        this.finish();
    }
}

Any ideas how I should resolve this?

TIA


Solution

  • The onCreateOptionsMenu is only called once, right before you open the OptionsMenu the first time. Instead use onPrepareOptionsMenu to call your startActivity(new Intent(this, PreferencesActivity.class));
    onPrepareOptionsMenuis called everytime you click on the Menu-Button.

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        startActivity(new Intent(this, PreferencesActivity.class));
        return super.onPrepareOptionsMenu(menu);
    }