如何从片段中更改菜单项图标?

问题描述 投票:4回答:1

如何从我的片段访问我的菜单,然后更改其中一个菜单项的图标?

我正在做的是查询我的本地数据库,以查看显示片段时是否存在某个条目。如果它显示实心图标,如果没有,则显示轮廓图标。

android android-fragments
1个回答
9
投票

在你的片段onCreate()方法中,你可以使用setHasOptionsMenu(true)来让你的片段处理不同的菜单项而不是它的根Activity。所以你可以在你的片段中做这样的事情:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

然后,您可以覆盖片段中的任何菜单生命周期方法:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_fragment, menu);
    // You can look up you menu item here and store it in a global variable by 
    // 'mMenuItem = menu.findItem(R.id.my_menu_item);'
}

@Override
public void onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    MenuItem menuItem = menu.findItem(R.id.menu_item_to_change_icon_for); // You can change the state of the menu item here if you call getActivity().supportInvalidateOptionsMenu(); somewhere in your code
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    // Handle actions based on the id field.
}
© www.soinside.com 2019 - 2024. All rights reserved.