Android menu only works once per application

I hit a weird issue with my Android app. In my main activity there is a menu attached to a menu button. The problem is that the menu button works exactly once. After clicking, the application must be restarted before the menu button will work again.

Code (sanitized):

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 preference 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 solve this?

TIA

+4
source share
3 answers

onCreateOptionsMenu is called only once, right before you open OptionsMenu for the first time. Instead, use onPrepareOptionsMenu to call startActivity(new Intent(this, PreferencesActivity.class));
onPrepareOptionsMenu is called every time you press the menu button.

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

The problem is that you are starting an Activity instead of displaying a menu. The usual way would be to inflate the menu inside onCreate Optionsmenu and have a settings item in that menu that, when pressed, shows the selection operation.

Tommy is right. If you want to start working immediately with preference (remember that this is an unusual behavior for an Android application), you can do this in onPrepareOptionsMenu. In normal mode, a menu is created once in the onCreateOptionsMenu callback, after which it is reused.

+1
source

After you click the menu button, you go to PreferencesActivity and whenever you click on it ... the first activity is closed due to the onBackPressed method.

Can you tell me what exactly you are looking for?

0
source

Source: https://habr.com/ru/post/1399981/


All Articles