How to know when are menu items in activity created?

21 Views Asked by At

I have an activity with a Toolbar showing an settings menu.

When I access the menu items via

            val icon0 = ResourcesCompat.getDrawable(resources, id0, null)
            (findViewById<View>(R.id.zone0) as? ItemView)?.setIcon(icon0)

in onCreate(...) of my activity the app crashes because findViewById returns null.

A few seconds after start, however I get a nun-null result from findViewById. 'zone0' is an ImageView located in the ToolBar.

Please note that I am NOT using fragments. I want to know - within the scope of my activity - WHEN my menu item view 'zone0' is accessible. From the docs I didn't see any callbacks indicating this.

From docs I read about menus:

Changing menu items at runtime

After the system calls onCreateOptionsMenu(), it retains an instance of the Menu you populate and will not call onCreateOptionsMenu() again unless the menu is invalidated for some reason. However, you should use onCreateOptionsMenu() only to create the initial menu state and not to make changes during the activity lifecycle.

If you want to modify the options menu based on events that occur during the activity lifecycle, you can do so in the onPrepareOptionsMenu() method. This method passes you the Menu object as it currently exists so you can modify it, such as add, remove, or disable items. (Fragments also provide an onPrepareOptionsMenu() callback.)

On Android 2.3.x and lower, the system calls onPrepareOptionsMenu() each time the user opens the options menu (presses the Menu button).

On Android 3.0 and higher, the options menu is considered to always be open when menu items are presented in the app bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().

Is there a solution to get notified when the menu items are available ?

0

There are 0 best solutions below