我试图从一组片段中添加一个项目到选项菜单。

我已经创建了一个新的MenuFragment类,并扩展了我希望包含菜单项的片段。代码如下:

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);
    }
}

科特林:

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似乎没有运行。


当前回答

如果上面的选项都不适合你,在你的片段中试试这个:

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


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { 
....
        toolBar = rootView.findViewById(R.id.import_contacts_toolbar)
        toolBar?.title = "Your title"
        toolBar?.subtitle = "yor subtitile"
        contactsActivity().setSupportActionBar(toolBar)
        toolBar?.inflateMenu(R.menu.import_contacts_menu)
...
}



    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.1 -> {

                return true
            }
            R.id.2 -> {

                return true
            }
        }
    
        return false
    }





    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        menu.clear()
        inflater.inflate(R.menu.import_contacts_menu, menu)
        super.onCreateOptionsMenu(menu, inflater)

        val search = menu.findItem(R.id.action_search)
        val searchView = search.actionView as SearchView
        searchView.requestFocus()

        val txtSearch = searchView.findViewById<View>(androidx.appcompat.R.id.search_src_text) as EditText
        txtSearch.hint = "Search..."
        txtSearch.setHintTextColor(Color.WHITE);
        txtSearch.setTextColor(Color.WHITE)

        try {
            val f: Field = TextView::class.java.getDeclaredField("mCursorDrawableRes")
            f.setAccessible(true)
            f.set(txtSearch, R.drawable.search_edit_text_cursor)
        } catch (ignored: Exception) {
            Log.d(TAG, "failed to expose cursor drawable $ignored")
        }

        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String): Boolean {
                return false
            }

            override fun onQueryTextChange(newText: String): Boolean {

                return true
            }
        })
        searchView.setOnCloseListener {
            
        }
    }

在我的例子中,我有一个搜索菜单项,它被设置为始终可见。这是它的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        app:showAsAction="always"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        android:title="Search"/>

    <item android:id="@+id/1"
        android:title="1">
    </item>

    <item android:id="@+id/2"
        android:title="2">
    </item>
</menu>

其他回答

调用super方法:

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)
    }

在代码中放入日志语句,以查看是否没有调用该方法,或者您的代码是否没有修改菜单。

同时确保你在onCreate(Bundle)中调用sethasoptionmenu (boolean)来通知片段它应该参与选项菜单处理。

如果上面的选项都不适合你,在你的片段中试试这个:

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


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { 
....
        toolBar = rootView.findViewById(R.id.import_contacts_toolbar)
        toolBar?.title = "Your title"
        toolBar?.subtitle = "yor subtitile"
        contactsActivity().setSupportActionBar(toolBar)
        toolBar?.inflateMenu(R.menu.import_contacts_menu)
...
}



    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.1 -> {

                return true
            }
            R.id.2 -> {

                return true
            }
        }
    
        return false
    }





    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        menu.clear()
        inflater.inflate(R.menu.import_contacts_menu, menu)
        super.onCreateOptionsMenu(menu, inflater)

        val search = menu.findItem(R.id.action_search)
        val searchView = search.actionView as SearchView
        searchView.requestFocus()

        val txtSearch = searchView.findViewById<View>(androidx.appcompat.R.id.search_src_text) as EditText
        txtSearch.hint = "Search..."
        txtSearch.setHintTextColor(Color.WHITE);
        txtSearch.setTextColor(Color.WHITE)

        try {
            val f: Field = TextView::class.java.getDeclaredField("mCursorDrawableRes")
            f.setAccessible(true)
            f.set(txtSearch, R.drawable.search_edit_text_cursor)
        } catch (ignored: Exception) {
            Log.d(TAG, "failed to expose cursor drawable $ignored")
        }

        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String): Boolean {
                return false
            }

            override fun onQueryTextChange(newText: String): Boolean {

                return true
            }
        })
        searchView.setOnCloseListener {
            
        }
    }

在我的例子中,我有一个搜索菜单项,它被设置为始终可见。这是它的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        app:showAsAction="always"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        android:title="Search"/>

    <item android:id="@+id/1"
        android:title="1">
    </item>

    <item android:id="@+id/2"
        android:title="2">
    </item>
</menu>

自androidx.activity:activity:1.4.0以来,有了一种新的方法来做到这一点

你应该使用菜单提供者API。

它的用法如下:

而不是叫super。setHasOptionMenu和实现oncreateoptionmenu你应该在onViewCreated中调用addMenuProvider。

一个例子:

class ExampleFragment : Fragment(R.layout.fragment_example) {

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    // The usage of an interface lets you inject your own implementation
    val menuHost: MenuHost = requireActivity()
  
    // Add menu items without using the Fragment Menu APIs
    // Note how we can tie the MenuProvider to the viewLifecycleOwner
    // and an optional Lifecycle.State (here, RESUMED) to indicate when
    // the menu should be visible
    menuHost.addMenuProvider(object : MenuProvider {
      override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
        // Add menu items here
        menuInflater.inflate(R.menu.example_menu, menu)
      }

      override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
        // Handle the menu selection
        return true
      }
    }, viewLifecycleOwner)
  }

来源:活动变更日志

我也遇到了同样的问题,但我认为最好总结并介绍让它工作的最后一步:

在Fragment的onCreate(Bundle savedInstanceState)方法中添加sethasoptionmenu (true)方法。 重写onCreateOptionsMenu(菜单菜单,MenuInflater膨胀器)(如果你想做一些不同的在你的片段的菜单)和onOptionsItemSelected(MenuItem项目)方法在你的片段。 在onOptionsItemSelected(MenuItem item) Activity的方法中,当菜单项操作将在onOptionsItemSelected(MenuItem item) Fragment的方法中实现时,确保返回false。

一个例子:

活动

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        case R.id.activity_menu_item:

            // Do Activity menu item stuff here
            return true;

        case R.id.fragment_menu_item:

            // Not implemented here
            return false;
        default:
            break;
    }

    return false;
}

片段

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

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    // Do something that differs the Activity's menu here
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        case R.id.activity_menu_item:

            // Not implemented here
            return false;
        case R.id.fragment_menu_item:

            // Do Fragment menu item stuff here
            return true;

        default:
            break;
    }

    return false;
}

在onCreate方法上添加setHasOptionMenu()

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

然后覆盖你的onCreateOptionsMenu

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.add("Menu item")
            .setIcon(android.R.drawable.ic_delete)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}