Wednesday, June 10, 2020

android kotlin - Menu overflow icon

MainActivity.kt

package com.example.jetpack

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.Menu
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 Overflow Icon"
        }
    }


    @SuppressLint("RestrictedApi")
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.toolbar_menu,menu)

        // 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"
        app:showAsAction="withText|always" />
    <item
        android:id="@+id/upload"
        android:title="Upload"
        android:icon="@drawable/ic_cloud_upload"
        app:showAsAction="never" />
    <item
        android:id="@+id/cancel"
        android:title="Cancel"
        android:icon="@drawable/ic_cancel"
        app:showAsAction="never" />
    <item
        android:id="@+id/settings"
        android:title="Settings"
        android:icon="@drawable/ic_settings"
        app:showAsAction="never" />
</menu>