How to Add a menu to the toolbar in Android (Kotlin)

  • by

Create a menu XML.

Right click on menu resource folder New> Menu resource file.

If the menu folder not found under the resource folder then right-click res folder New > Android Resource Directory in resource-type click menu on then press ok will create a menu directory inside res folder.

Insider your menu resource folder paste the code.

<?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/addPost"
        android:icon="@drawable/ic_post_add"
        android:title="@string/post"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/setting"
        android:icon="@drawable/ic_settings"
        android:title="@string/setting"
        app:showAsAction="never" />

</menu>

Inflate the menu XML

Now we have to use menu XML in our toolbar.

In your activity add the following method.

add_post_menu_item is your menu file.

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        val inflater = menuInflater
        inflater.inflate(R.menu.add_post_menu_item, menu)
        return true
    }

Handle Menu Click

For handling the menu click. Add this code in your activity

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.addPost -> {
                Toast.makeText(this,"Add Post Clicked",Toast.LENGTH_SHORT).show()
                true
            }
            R.id.setting -> {
                Toast.makeText(this,"Setting Clicked",Toast.LENGTH_SHORT).show()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *