如何在Android中将选项菜单添加到片段 [英] How to add Options Menu to Fragment in Android

查看:97
本文介绍了如何在Android中将选项菜单添加到片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从一组片段中向选项菜单添加项目。

I am trying to add an item to the options menu from a group of fragments.

我创建了一个新的 MenuFragment 类,并将其扩展为希望包含菜单项的片段。这是代码:

I have created a new MenuFragment class and extended this for the fragments I wish to include the menu item in. Here is the code:

Java:

public class MenuFragment extends Fragment {

    MenuItem fav;

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

    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        fav = menu.add("add");
        fav.setIcon(R.drawable.btn_star_big_off);
    }
}

Kotlin:

class MenuFragment : Fragment {

    lateinit var fav: MenuItem

    override fun onCreate(savedInstanceState: Bundle) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        fav = menu.add("add");
        fav.setIcon(R.drawable.btn_star_big_off);
    }
}

由于某些原因, onCreateOptionsMenu 似乎没有运行。

For some reason the onCreateOptionsMenu appears not to run.

推荐答案

调用超级方法:

Java:

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

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Add your menu entries here
        super.onCreateOptionsMenu(menu, inflater);
    }

科特琳:

    override fun void onCreate(savedInstanceState: Bundle) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        // TODO Add your menu entries here
        super.onCreateOptionsMenu(menu, inflater)
    }

在代码中添加日志语句,以查看是否未调用该方法或菜单是否未

Put log statements in the code to see if the method is not being called or if the menu is not being amended by your code.

还请确保您在中调用 setHasOptionsMenu(boolean) onCreate(Bundle)通知片段应该参与选项菜单处理。

Also ensure you are calling setHasOptionsMenu(boolean) in onCreate(Bundle) to notify the fragment that it should participate in options menu handling.

这篇关于如何在Android中将选项菜单添加到片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆