Menu Flashcards

1
Q

How to add an options menu to the Fragment?

A

Call setHasOptionsMenu(true) in Fragment.onCreateView

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to handle menu item clicks?

A
CUSTOM HANDLING
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// handle using item.itemId (matches menu xml ^item^ ids)
return true
}

WHEN MENU ITEM IDs MATCH FRAGMENT IDs IN NAV_GRAPH
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return NavigationUI.onNavDestinationSelected(item, requireView( ).findNavController( )) || super.onOptionsItemSelected(item)
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Which dependency is required to implement a navigation drawer?

A

implementation “com.google.android.material:material:$version”

(The nav drawer is part of the Material Components for Android library (material.io))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to add a navigation drawer to a layout xml?

A
  1. Add a menu xml with an ^item^ element for each option.
  2. Wrap the Activity’s root view in a ^androidx.drawerlayout.widget.DrawerLayout^ tag, wrapped in turn by a ^layout^ tag
3. Add the following just before the closing ^/layout^ tag:
^com.google.android.material.navigation.NavigationView
   android:id="@+id/navView"
   android:layout_width="wrap_content"
   android:layout_height="match_parent"
   android:layout_gravity="start"
   app:headerLayout="@layout/nav_header"
   app:menu="@menu/navdrawer_menu" /^
  1. Add the following to Activity.onCreate( ) or Fragment.onCreateView( ) :
    NavigationUI.setupWithNavController(binding.navViewXmlId, navController, drawerLayout)
    // third parameter, drawerLayout (from binding) is optional - it adds navigation drawer from app bar’s drawer button.
5. override fun onSupportNavigateUp(): Boolean {
   val navController = this.findNavController(R.id.myNavHostFragment)
   return NavigationUI.navigateUp(navController, drawerLayout)
}
// NB This implementation is slightly different if there is an options menu without a nav drawer (see Activities & Fragments, card 10)

As with the options menu, if the item id’s match the fragment id’s in the nav_graph then no need to implement clickListeners

How well did you know this?
1
Not at all
2
3
4
5
Perfectly