Skip to content

Instantly share code, notes, and snippets.

@qamarelsafadi
Last active January 19, 2024 12:52
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save qamarelsafadi/bcec50f59606441b3526f41a96e9e822 to your computer and use it in GitHub Desktop.
Save qamarelsafadi/bcec50f59606441b3526f41a96e9e822 to your computer and use it in GitHub Desktop.
This gist will help you to get started with the new menu implementation way, you can find 2 extensions that will help you not repeat a huge code, Enjoy it.
// Step 1 : implement the new activity dependency in you gradle
implementation 'androidx.activity:activity-ktx:1.5.1'
// if you are using compose
implementation 'androidx.activity:activity-compose:1.5.1'
/* ---------------------------------------------- Activity Extension -------------------------------------------------------*/
fun AppCompatActivity.bindMenu(
@MenuRes menuRes: Int,
onMenuItemSelected: (MenuItem) -> Unit
): MenuProvider{
val menuProvider = object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(menuRes, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
onMenuItemSelected(menuItem)
return true
}
}
addMenuProvider(menuProvider)
return menuProvider
}
// USAGE
class MainActivity : AppCompatActivity(R.layout.activity_main) ){
setSupportActionBar(tb)
val provider = bindMenu(R.menu.home_menu){
/*
* do what you want on your menu item click listener
* */
}
// if you want to remove it in a specific action
removeMenuProvider(provider)
}
/* ---------------------------------------------- Fragment Extension -------------------------------------------------------*/
fun FragmentActivity.bindMenu(
menuHost: MenuHost,
@MenuRes menuRes: Int,
lifecycleOwner: LifecycleOwner,
onMenuItemSelected: (MenuItem) -> Unit
): MenuProvider{
val menuProvider = object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(menuRes, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
onMenuItemSelected(menuItem)
return true
}
}
menuHost.addMenuProvider(menuProvider,lifecycleOwner, Lifecycle.State.RESUMED)
return menuProvider
}
// USAGE
class HomeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
val menuHost: MenuHost = requireActivity()
val provider = requireActivity().bindMenu(
menuHost = menuHost,
menuRes = R.menu.home_menu,
lifecycleOwner = viewLifecycleOwner) { menuItem ->
/*
* do what you want on your menu item click listener
* */
}
// if you want to remove it in a specific action
menuHost.removeMenuProvider(provider)
}
}
@anupdey99
Copy link

Helpful. Thanks for sharing! 🤗

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment