udacity / andfun-kotlin-android-trivia

Other
197 stars 481 forks source link

deprecated way for options Menu #54

Open Ghanem21 opened 2 years ago

Ghanem21 commented 2 years ago

setHasOptionsMenu(true) is deprecated at title fragment onCreateOptionsMenu is deprecated at title fragment onOptionsItemSelected is deprecated at title fragment

Bellily commented 7 months ago

Here is my code for adding the overflow menu. I followed https://stackoverflow.com/questions/71917856/sethasoptionsmenuboolean-unit-is-deprecated-deprecated-in-java

class TitleFragment : Fragment() {

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    val binding: FragmentTitleBinding = DataBindingUtil.inflate(
        inflater, R.layout.fragment_title, container, false
    )
    //Enable inject of own implementation
    val menuHost: MenuHost = requireActivity()

    binding.playButton.setOnClickListener(
        Navigation.createNavigateOnClickListener(R.id.action_titleFragment_to_gameFragment)
    )
    menuHost.addMenuProvider(object : MenuProvider {
        override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
            // Add menu items here
            menuInflater.inflate(R.menu.overflow_menu, menu)
        }

        override fun onMenuItemSelected(item: MenuItem): Boolean {
            //Handle menu item selection
            return when (item.itemId) {
                R.id.aboutFragment -> {
                    NavigationUI.onNavDestinationSelected(
                        item,
                        requireView().findNavController()
                    )
                    true
                }
                // More menu-items could be added here as part of the when-logic
                else -> false

            }
        }
    })
    return binding.root
}

}