Reputation: 123
I have a toolbar in my MainActivity.kt
which has assigned the app:menu="@menu/top_menu
:
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:gravity="center_vertical">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_scrollFlags="scroll"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:title="@string/app_name"
app:fontFamily="@font/roboto_slab_bold"
app:menu="@menu/top_menu"
android:background="@color/colorWhite"
app:titleTextColor="@color/colorPrimary" />
</com.google.android.material.appbar.AppBarLayout>
And this top_menu that I have assigned to has this code:
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/itemSettings"
android:title="@string/title_activity_settings"
app:showAsAction="never" />
</menu>
The problem is, I can't access the Menu Item using the code:
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.itemSettings -> Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show()
}
return true
}
What do I need to do to assign this code to the menu that I have?
Upvotes: 0
Views: 663
Reputation: 1316
I think you need inflate your menu:
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.top_menu, menu)
super.onCreateOptionsMenu(menu, inflater)
}
Upvotes: 1