gpt4 book ai didi

Android:根据所选 fragment 更改菜单

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

我有不同的 fragment ,但我想更改选项菜单。我希望只有“Solicitudes”有它

The fragment that I want to have this option

This fragment shouldn't have it

我有一个包含 main.xml 的菜单文件夹,实际上我创建了另一个没有此设置选项的 main2.xml,但我不知道如何更改它

到目前为止,这是我的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);

mTitle = mDrawerTitle = getTitle();

fragment = new History();

oncreate:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

历史 fragment 的代码:

public class History extends Fragment {
public static final String ARG_HISTORY = "arg_history";

public History() {
// Empty constructor required for fragment subclasses
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.history, container, false);
return rootView;
}

最佳答案

在您的 Fragment 中,您需要说明此 Fragment 控制菜单。

在您的 FragmentonCreate 中。

setHasOptionsMenu(true);

现在您可以在 Fragment 中实现以下内容以隐藏您不想要的 MenuItem

    @Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.findItem(R.id.unwanted_item).setVisible(false);
}

确保在 Fragment 中执行相反的操作,您确实需要 MenuItem

如果你想添加一个 MenuItem,它不在你的 Activity 加载的 Menu 中,请在 onCreateOptionsMenu 中执行以下操作 在你的 Fragment 中。

    @Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_to_add_to_original, menu);
super.onCreateOptionsMenu(menu, inflater);
}

关于Android:根据所选 fragment 更改菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34597334/

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