0

我希望能够在选择菜单项后禁用它。也就是说,菜单项仅在第一次设置时可用。然后,它应该被完全禁用。我怎样才能做到这一点?

我尝试了以下方法:

  MenuItem mi=menu.findItem(R.id.item1));

并在“firstrun”之后使用此代码禁用它

 mi.setEnabled(false); 

但是,一旦我强制停止应用程序并再次返回它。菜单项已启用。如何防止这种情况并永久禁用它?

谢谢。

4

1 回答 1

3

You have to persist your data somewhere. In this case, I'd suggest using Shared Preferences which is the preferred way to store simple booleans and other small data, each with a specific key. In your case, once the user has clicked on the menu item, call

// Where this is a Context such as your Activity
SharedPreferences sp = PreferenceManager.getSharedPreferences(this);
sp.edit().putBoolean("MENU_CLICK", true).apply();
// Use commit() in place of apply() if you support pre-Gingerbread devices

Then in your onPrepareOptionsMenu(), retrieve the shared preference by using

SharedPreferences sp = PreferenceManager.getSharedPreferences(this);
// default false to show on first run
final boolean haveClickedMenu = sp.getBoolean("MENU_CLICK", false);
mi.setEnabled(!haveClickedMenu);
于 2013-07-07T21:11:49.457 回答