gpt4 book ai didi

java - 操作栏中项目标题的动态变化

转载 作者:行者123 更新时间:2023-11-29 03:26:43 25 4
gpt4 key购买 nike

我想做的是:通过 onClick 方法更改 Action Bar 中项目的标题。onCreateOptionsMenu代码:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return super.onCreateOptionsMenu(menu);
}

我的option_menu.xml菜单:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/state"
android:title="@string/title_not_connected"
android:showAsAction="ifRoom" />
</menu>

标题应从下面类中的onClick 方法更改:

@SuppressLint("ValidFragment")
public class ReceiveSectionFragment extends Fragment {
public NotificationCenter mNotificationCenter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.receive, container, false);
mNotificationCenter = new NotificationCenter();
rootView.findViewById(R.id.bt_server_start)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MenuItem item = (MenuItem) menu.findItem(R.id.state);
item.setTitle(TAG);
}
});
}
}

如您所见,我试图通过 Id 在菜单中查找此项目,但出现此错误:The method findItem(int) is undefined for the type R.menu。我正在使用 fragment ,ReceiveSectionFragment 使用 R.layout.receive 布局。

我该如何处理这个问题?可能是我用错了方法做错了。

我没有使用 ActionBar Sherlock。

最佳答案

当您想要更改 ActionBar 菜单时,您必须调用 InvalidateOptionsMenu

然后您可以覆盖 onCreateOptionsMenu 以使用您的更改重建菜单。您不能在为构建菜单提供的方法之外编辑菜单。

每次您调用 InvalidateOptionsMenu 时,您的菜单都会通过 onCreateOptionsMenu 方法重建,因此您需要在那里进行所有更改。

http://developer.android.com/reference/android/app/Activity.html#invalidateOptionsMenu()

http://developer.android.com/reference/android/app/Activity.html#onCreateOptionsMenu(android.view.Menu)

无论您是否使用 ActionBarSherlock 都是如此。

例如:

设置一个变量来保存标题

String MyMenuTitle = "Default Menu";

你的 OnClick

public void onClick(View view) {
MyMenuTitle = "My New Menu Title";
}

您的菜单构建代码。

@Override
public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.option_menu, menu);

MenuItem item = menu.findItem(R.id.state);
item.setTitle(MyMenuTitle);

return super.onCreateOptionsMenu(menu);
}

关于java - 操作栏中项目标题的动态变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20684690/

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