Kotlin: Create menu

Topics interesting only for Kotlin / Android / SQLite programmers

Link to this posting

Postby Ursego » 26 Dec 2019, 15:19

@ If res/menu directory doesn't exist: right click "res" directory > New > Directory > enter the directory name "menu" > OK.

@ Right click "menu" directory > New > File > enter the menu name "XXX_activity_menu" > OK > XML > OK > The menu designer opened.

@ Make its text:

Code: Select all
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"

        android:id="@+id/<your menu item id>"
        app:showAsAction="never" /> << or "ifRoom", or "always"

@ Choose an icon: switch the menu XML from Text to Design view > in Component Tree, click the menu item > Attributes > icon > click on the vertical line ("Pick a resource").

@ Add to the Activity, for which the menu is created:

Code: Select all
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        (menu as MenuBuilder).setOptionalIconsVisible(true) // remove this line if your menu items don't have icons
        menuInflater.inflate(R.menu.batch_list_activity_menu, menu)
        return super.onCreateOptionsMenu(menu)

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            R.id.<your menu item id> -> {
                val intent = Intent(this, changeToTheActivityYouWantToOpen::class.java)
        return super.onOptionsItemSelected(item!!)


If you want to make a menu item visible (or invisible) in code depending on a runtime condition, do the following:

@ If the menu item must be invisible by default, then, when you define it in the menu XML file, add the following property to it:

Code: Select all

@ In the Activity, for which the menu is created, override the function onPrepareOptionsMenu(). In the following example, I show the menu item "Группа на ФБ (на русском)" (which means "FB Group (in Russian)") only if the current language is Russian (of course, you should change the condition to yours):

Code: Select all
    override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
        if (AppPrefs.getString(PrefKey.LANG, this) == Lang.RUSSIAN) {
            val openFbGroupRuMenuItem = menu?.findItem(R.id.open_fb_group_ru)
            openFbGroupRuMenuItem!!.isVisible = true // or false if the menu item is invisible by default

        return super.onPrepareOptionsMenu(menu)
User avatar
Site Admin
Posts: 140
Joined: 19 Feb 2013, 20:33

IF you want to ((lose weight) OR (have unbelievable (brain function AND mental clarity))) THEN click:

Traffic Counter

free counters

eXTReMe Tracker