Options Menu
Notes
The options menu is the primary collection of menu items for an activity. It's where you should place actions that have a global impact on the app. The options menu is displayed when the user presses the Menu button on the device. You can add items to the options menu from the XML file by adding a <menu>element to your XML layout file. Each item in the options menu is represented by a <item> element and can provide additional actions for the user
Menu Resource File (res/menu/menu_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Menu item for Settings -->
<item
android:id="@+id/action_settings"
android:title="Settings"
android:orderInCategory="100"
android:showAsAction="never" />
<!-- Menu item for About -->
<item
android:id="@+id/action_about"
android:title="About"
android:orderInCategory="101"
android:showAsAction="never" />
</menu>
<!-- Save this file as res/menu/menu_main.xml -->MainActivity - Inflating the Options Menu
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Your initialization code here
}
// Inflate the options menu (app bar menu)
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
// Use the menu inflater to inflate the menu_main.xml file
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
// Handle menu item clicks
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_settings -> {
// Handle Settings click
Toast.makeText(this, "Settings clicked", Toast.LENGTH_SHORT).show()
true
}
R.id.action_about -> {
// Handle About click
Toast.makeText(this, "About clicked", Toast.LENGTH_SHORT).show()
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
/*
Place this code in your MainActivity.kt file (usually under app/src/main/java/your/package/name/MainActivity.kt).
Ensure that you have created the menu_main.xml file in the res/menu folder as shown above.
*/