Remove overflow menu 3 dots in fragment

Viewed 403

I have a fragment that needs to have a custom menu. Below is the code which is added to my fragment.

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

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

My actionbar_menu is as follows:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/search"
        android:icon="@drawable/search"
        android:title="Search"
        app:showAsAction="always"
        tools:ignore="AlwaysShowAction" />
</menu>

I only want this search icon to be present in the toolbar. What happens is its adding overflow menu too. How can I remove the overflow menu?

UPDATE: I am getting this issue only in mobiles. In tablet emulators its not showing up.

2 Answers

It worked when I called the same in different way.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    setHasOptionsMenu(true)
}

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

First of all remove menu inflate override functions from fragment container activity.

Fragment class:

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    setHasOptionsMenu(false)         // Show/Hide Icon
    return inflater.inflate(R.layout.fragment_first, container, false)
}

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    inflater.inflate(R.menu.menu_main, menu)    // Give your desire menu.xml
}

This function can show/hide overflow menu icon setHasOptionsMenu()

  • If you use setHasOptionsMenu(true), then menu icon is appeared on toolbar.
  • else setHasOptionsMenu(false), then menu icon is hidden on toolbar.
Related