244
CHAPTER 9: User Interface
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay"/>
Inside the activity’s onCreate(...) method, we need to tell Android OS that we are using an
app bar. To do so, register the app bar via the following:
setSupportActionBar(toolbar)
Also,
in the activity, overwrite onCreateOptionsMenu(...) to create the menu, and overwrite
onOptionsItemSelected(...) to listen to menu click events.
override
fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.getItemId()) {
menu_item1 -> {
Toast.makeText(this,"Item 1",
Toast.LENGTH_LONG).show()
return true
}
menu_item2 -> {
Toast.makeText(this,"Item 2",
Toast.LENGTH_LONG).show()
return true
}
else ->
return
super.onOptionsItemSelected(item)
}
}
override
fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater inflate(R.menu.my_menu, menu)
return true
}
What is left is the definition of the menu itself. Inside res/menu, add an XML file called my_
menu.xml with the following contents:
"http://schemas.android.com/apk/res/android">
android:title="@string/title_item1"/>
android:title="@string/title_item2"/>