MainActivity.kt
package com.example.jetpack
import android.annotation.SuppressLint
import android.graphics.*
import android.os.Build
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 Icon Color"
}
}
@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)
}
// change menu icon color programmatically
menu?.apply {
for(index in 0 until this.size()){
val item = this.getItem(index)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
item.icon.colorFilter = BlendModeColorFilter(
Color.BLUE, BlendMode.SRC_IN
)
}else{
item.icon.setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_IN)
}
}
}
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="always" />
<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>