• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

onCreateOptionsMenu is never called

umtblbl

Member
Hi my friends, I want to make a search bar and want to capture each letter entry. However, onCreateOptionsMenu is not called at all, no debug falls on that line.

Code:
class PhotoFragment : Fragment() {

    companion object {
        fun newInstance() = PhotoFragment()
    }

    @Inject
    lateinit var dataManager: DataManager

    private lateinit var viewModel: PhotoViewModel

    var searchList: MutableList<String> = ArrayList()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.photo_fragment, container, false)

        (activity as AppCompatActivity).supportActionBar
        view.toolbarProfileSearch.setNavigationOnClickListener { context }
        setHasOptionsMenu(true)

        return view

    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        componentFragment.inject(this)
        viewModel = ViewModelProviders.of(this, PhotoFragmentFactory(dataManager)).get(PhotoViewModel::class.java)
        setHasOptionsMenu(true)


        viewModel.profileResult.observe(this, Observer { profileResult ->
            loadPicture(profileResult)
        })


        btnGetProfilePicture.setOnClickListener {
            viewModel.callProfileResult(editUserName.text.toString())
        }


    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {

        inflater.inflate(R.menu.toolbar_menu_searchprofile, menu)
        val searchItem = menu.findItem(R.id.search)
        val searchView = searchItem.actionView as SearchView

        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                searchView.clearFocus()
                searchView.setQuery("", false)
                searchItem.collapseActionView()
                Log.d("SEARCH1", "$query")

                return true

            }

            override fun onQueryTextChange(newText: String?): Boolean {
                Log.d("SEARCH2", "$newText")
                return false

            }
        })


        super.onCreateOptionsMenu(menu, inflater)
    }
}
 
I used
in onCreateView -> setHasOptionsMenu(true)
onActivityCreated -> (activity as AppCompatActivity).setSupportActionBar(toolbarProfileSearch)
solved.
 
Back
Top Bottom