gpt4 book ai didi

Android - 正确使用 invalidateOptionsMenu()

转载 作者:IT老高 更新时间:2023-10-28 21:47:47 25 4
gpt4 key购买 nike

我在 invalidateOptionsMenu() 上搜索了很多,我知道它的作用。但我想不出任何现实生活中这种方法有用的例子。

我的意思是,例如,假设我们想在 ActionBar 中添加一个新的 MenuItem,我们可以简单地从 onCreateOptionsMenu(Menu menu ) 并在任何按钮的操作中使用它。

现在我真正的问题是,是否遵循 only 使用 invalidateOptionsMenu() 的方式?

bool _OtherMenu;
protected override void OnCreate (Bundle bundle)
{
_OtherMenu = false;
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate
{
if(_OtherMenu)
_OtherMenu = false;
else
_OtherMenu = true;

InvalidateOptionsMenu ();
};
}

public override bool OnCreateOptionsMenu (IMenu menu)
{
var inflater = this.SupportMenuInflater;
if(_OtherMenu)
inflater.Inflate (Resource.Menu.another_menu, menu);
else
inflater.Inflate (Resource.Menu.main_activity_menu, menu);

return base.OnCreateOptionsMenu (menu);
}

单击该按钮会出现一个不同的菜单。再次单击该按钮,将出现上一个菜单。

附:对不起 C# 语法。

最佳答案

invalidateOptionsMenu() 用来表示Android,菜单的内容发生了变化,需要重绘菜单。例如,您单击一个在运行时添加另一个菜单项或隐藏菜单项组的按钮。在这种情况下,您应该调用 invalidateOptionsMenu(),以便系统可以在 UI 上重新绘制它。此方法是 OS 调用 onPrepareOptionsMenu() 的信号,您可以在其中实现必要的菜单操作。此外,OnCreateOptionsMenu()在activity(fragment)创建过程中只被调用一次,因此该方法无法处理运行时菜单的变化。

全部可以在 documentation 中找到:

After the system calls onCreateOptionsMenu(), it retains an instance of the Menu you populate and will not call onCreateOptionsMenu() again unless the menu is invalidated for some reason. However, you should use onCreateOptionsMenu() only to create the initial menu state and not to make changes during the activity lifecycle.

If you want to modify the options menu based on events that occur during the activity lifecycle, you can do so in the onPrepareOptionsMenu() method. This method passes you the Menu object as it currently exists so you can modify it, such as add, remove, or disable items. (Fragments also provide an onPrepareOptionsMenu() callback.)

On Android 2.3.x and lower, the system calls onPrepareOptionsMenu() each time the user opens the options menu (presses the Menu button).

On Android 3.0 and higher, the options menu is considered to always be open when menu items are presented in the action bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().

关于Android - 正确使用 invalidateOptionsMenu(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27984041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com