android: changing option menu items programmatically

前端 未结 12 1962
终归单人心
终归单人心 2020-12-02 09:33

Is it possible to change the option menu items programmatically? Can anyone provide me with an example please?

Also, I want to disable certain items, so that they do

12条回答
  •  孤街浪徒
    2020-12-02 10:22

    Kotlin Code for accessing toolbar OptionsMenu items programmatically & change the text/icon ,..:

    1-We have our menu item in menu items file like: menu.xml, sample code for this:

      
     
    
     
    

    2- Define a variable for accessing menu object in class :

    var menu: Menu? = null
    

    3- initial 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 the menu items inside your code or fun :

    private fun initialBalanceMenuItemOnToolbar() {
    var menuItemBalance = menu?.findItem(R.id.balance)
        menuItemBalance?.title = Balance?.toString() ?: 0.toString()
        // for change icon : menuWalletBalance?.icon
    }
    

提交回复
热议问题