Handle items from an Action Bar outside the scope of onCreateOptionsMenu ()

6

I have in my Action Bar an item to display progress (a ProgressBar) if a request is occurring. When the request occurs, I must show the ProgressBar and hide the other items, when the request ends, I must hide the ProgressBar and show the other items.

Dictionaries

The request, that is, my AsyncTask, is executed when I start my Activity (in fact, it is a Fragment), that is, before the operating system invokes the creation of the menu with onCreateOptionsMenu() .

I need to retrieve and manipulate the items from a Action Bar outside the scope of the onCreateOptionsMenu() , ie at the beginning and at the end of AsyncTask.

Note

AsyncTask is declined in a separate class. Activity delegates to a class that manipulates and manages the methods of this AsyncTask.

How to manipulate an ActionBar outside the scope of onCreateOptionsMenu() ?

    
asked by anonymous 17.09.2015 / 21:07

3 answers

2

Can not manipulate something before it has been created. Therefore, you will only have access to the Menu after the onCreateOptionsMenu() method has been executed.

I suggest you do the following:

  • Declare a private variable to save the reference to Menu : mMenu .
  • Declare a method to execute AsyncTask .
  • In the onCreateOptionsMenu() method, make sure mMenu is null if you save the reference to the menu and call the method that runs AsyncTask .
  • In method onStart() check that mMenu is null, if not is calling the method that runs AsyncTask

So when Activity is created, AsyncTask is thrown in the onCreateOptionsMenu() method, in other situations, arising from the normal Activity lifecycle , AsyncTask is thrown in the onStart() method.

You will need to pass the Menu reference to your AsyncTask .

    
21.09.2015 / 16:49
2

You can not manipulate your Menu before it's even created.

The form I believe to be most correct is to run your AsyncTask after the onCreateOptionsMenu() method is executed, and pass Menu to its AsyncTask per parameter.

    
17.09.2015 / 22:15
0

You can use the   invalideOptionsMenu()

That will force the method call onCreateOptionsMenu()

    
18.09.2015 / 15:01