Kotlin code for programmatically accessing the OptionsMenu toolbar and changing text / icon, ..:
1-We have a menu item in the file of menu items, such as: menu.xml, example code for this:
<?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/balance" android:title="0" android:orderInCategory="100" app:showAsAction="always" /> </menu>
2- Define a variable to access the menu object in the class:
var menu: Menu? = null
3- initialize it in onCreateOptionsMenu:
override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main, menu) this.menu = menu return true }
4- Access to menu items inside your code or entertainment:
private fun initialBalanceMenuItemOnToolbar() { var menuItemBalance = menu?.findItem(R.id.balance) menuItemBalance?.title = Balance?.toString() ?: 0.toString()
Hamed Jaliliani Dec 12 '18 at 15:00 2018-12-12 15:00
source share