To create Toolbar menu:
- Create Menu in XML file in menu folder
res/menu/your_menu_name.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/search"
android:title="@string/search"
android:icon="@drawable/ic_search"
app:showAsAction="ifRoom" <!-- ifRoom means if free space then only showuo -->
/>
<item
android:id="@+id/logout"
android:title="@string/logout"
android:icon="@android:drawable/ic_secure"
/>
</menu>
- In activity, Override
onCreateOptionMenu()
1
2
3
4
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.your_menu_name, menu)
return super.onCreateOptionsMenu(menu)
}
- To access Menu press, Override
onOptionItemSelected()
1
2
3
4
5
6
7
8
9
10
11
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.search -> {
// do your stuff here
}
R.id.logout -> {
// do your stuff here
}
return super.onOptionsItemSelected(item)
}