MainActivity.kt
package com.example.jetpack
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.view.menu.MenuBuilder
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val actionBar = supportActionBar
actionBar?.apply {
title = "Menu Add Remove Item"
}
}
@SuppressLint("RestrictedApi")
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.toolbar_menu,menu)
menu?.apply {
// ----------------- add a new item to menu ----------------
// add new item to menu
val newItem:MenuItem = menu.add(
Menu.NONE, // group id
2, // item id
1, // order
"New Item" // title
)
// set new item's icon
newItem.setIcon(R.drawable.ic_check_circle)
// set new item show as action flags
newItem.setShowAsActionFlags(
MenuItem.SHOW_AS_ACTION_ALWAYS or
MenuItem.SHOW_AS_ACTION_WITH_TEXT
)
// menu new item click listener
newItem.setOnMenuItemClickListener {
Toast.makeText(this@MainActivity,
"New Item Clicked",
Toast.LENGTH_SHORT)
.show()
true
}
// ----------------- remove an item from menu ----------------
menu.removeItem(R.id.cancel)
// ----------------- update an item in menu ----------------
menu.findItem(R.id.settings).apply {
title = "Updated Title"
}
}
// To display icon on overflow menu
if (menu is MenuBuilder) {
menu.setOptionalIconsVisible(true)
}
return super.onCreateOptionsMenu(menu)
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"/>
res/menu/toolbar_menu.xml
<?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/download"
android:title="Download"
android:icon="@drawable/ic_arrow_download"
android:orderInCategory="0"
app:showAsAction="withText|always" />
<item
android:id="@+id/upload"
android:title="Upload"
android:icon="@drawable/ic_cloud_upload"
android:orderInCategory="2"
app:showAsAction="never" />
<item
android:id="@+id/cancel"
android:title="Cancel"
android:icon="@drawable/ic_cancel"
android:orderInCategory="3"
app:showAsAction="never" />
<item
android:id="@+id/settings"
android:title="Settings"
android:icon="@drawable/ic_settings"
android:orderInCategory="4"
app:showAsAction="never" />
</menu>