In Kotlin, declaration for Activity, Fragment and PreferenceFragmentCompat
Activity
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.main_menu, menu) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { // Handle the menu selection return true } }) } }
Fragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { // The usage of an interface lets you inject your own implementation val menuHost: MenuHost = requireActivity() menuHost.addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { // Add menu items here menuInflater.inflate(R.menu.main_menu, menu) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { // Handle the menu selection return when (menuItem.itemId) { R.id.action_menu1 -> { // todo menu1 true } R.id.action_menu2 -> { // todo menu2 true } else -> false } } }, viewLifecycleOwner, Lifecycle.State.RESUMED) }
PreferenceFragmentCompat
val menuHost: MenuHost = requireHost() as MenuHost //Same declaration with Fragment
Use MenuProvider interface
class FirstFragment : Fragment(), MenuProvider { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val menuHost: MenuHost = requireActivity() menuHost.addMenuProvider(this, viewLifecycleOwner, Lifecycle.State.RESUMED) } override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { // Add menu items here menuInflater.inflate(R.menu.second_menu, menu) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { // Handle the menu selection return when (menuItem.itemId) { R.id.menu_clear -> { // Do stuff... true } R.id.menu_refresh -> { // Do stuff... true } else -> false } }, viewLifecycleOwner, Lifecycle.State.RESUMED) }