Perhaps I'm missing the obvious, but my menu is only been created and populated when onCreateOptionsMenu(Menu menu) is called, as in this example, and this only seem to be called after I press the menu button.
I would like to populate the menu upon the creation of the activity, how can achieve that?
UPDATE:
Perhaps a better question would be:
How can I get the Menu instance of my Activity?
Thanks
Create a class which holds those states then set your enabled/checked etc from the properties of that class in onCreateOptionsMenu()
class MenuStates{
public static boolean userDidPressTheButton;
public static boolean serverDidRespond;
public static boolean colorWasChanged;
}
void someEventHandler(){
MenuStates.userDidPressTheButton = true;
}
void onCreateOptionsMenu(){
myCheckBox.setChecked(MenuStates.userDidPressTheButton);
}
[EDIT]
You don't say why you want to get the menu instance. One approach:
Menu optsMenu;
...
// this is called once only before the end of the Activity onCreate().
onCreateOptionsMenu(Menu menu){
opstMenu = menu;
super.onCreateOptionsMenu(menu);
}
Following that, modify your menu as you wish. Do any "as it pops" up work in onPrepareOptionsMenu().
The key understanding is the difference between onCreateOptionsMenu() and onPrepareOptionsMenu().
[MORE EDIT]
To completely control the thing yourself:
Menu optsMenu;
onCreate(){
openOptionsMenu() // the menu won't show in onCreate but onCreateOptionsMenu is shown
closeOptionsMenu()
}
onCreateOptionsMenu(Menu menu){
optsMenu = menu;
}
onPrepareOptionsMenu(Menu menu){
menu.clear();
for (int i=0;ioptsMenu.size();i++){
menu.add(optsMenu.get(i).getTitle());
}
return super.onPrepareOptionsMenu(menu);
}
From the docs
You can safely hold on to menu (and any items created from it), making modifications to it as desired, until the next time onCreateOptionsMenu() is called.
http://developer.android.com/reference/android/app/Activity.html#onCreateOptionsMenu%28android.view.Menu%29
Related
It is simple information question. According to page situation i want to block user click on toolbar overflowIcon. I look for methods but cannot find a way. How can i disable onClick on OverflowIcon ?
If you need to disable it in ACTIVITY, Don't use this lines,
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
If it is in FRAGMENT, Use
setHasOptionsMenu(false); // inside of onCreateView
Let you consider, You have 3 icons (Home,Search,LogOut).
You don't want to show 1st icon in any fragment but have to show the 2nd & 3rd means,
setHasOptionsMenu(true); // inside of onCreateView
AND
Create a following method in Fragment,
#Override
public void onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.home).setVisible(false);
menu.findItem(R.id.search).setVisible(true);
menu.findItem(R.id.logout).setVisible(true);
}
Refer this :
http://kiddyandroid.blogspot.in/2016/03/fragment.html
The regular way to change programmatically menu item icon is save reference to the menu after onCreateOptionsMenu() called:
private Menu mOptionsMenu;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
mOptionsMenu = menu;
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
and then access it like: mOptionsMenu.findItem(R.id.action_something).setIcon(R.mipmap.new_icon);
My question is how to set new icon before onCreateOptionsMenu() called - so I don't have reference to the menu?
Thanks,
I don't think there is a way to get the reference to the menu before onCreateOptionsMenu(). Also why would you want to set an icon before the onCreateOptionsMenu?
Apologies for posting it as an answer as I need 50 points to be able to comment.
I've tried to find an answer about this but with no luck. I have a fragment that has an a menu item called 'menu_roi_result_calc'. Every time there is a screen rotation, a new menu item is created. The code is shown below:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_roi_result_calc, menu);
return true;
}
However, after a couple of screen rotations, this is what I get:
I get the feeling this is due to the fact that the menu items are being recreated at every rotation, therefore adding a new item every time a rotation occurs. How do I get this to stop? How can I check if the item is there and prevent from recreating it again? Any code example would be greatly appreciated.
You must clear your menu object before adding items. I had the same problem and this was the best solution that I've found.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.menu_roi_result_calc, menu);
super.onCreateOptionsMenu(menu, inflater);
}
I found out what the issue was. I was not reusing the original tagged fragments. All I had to do was make sure to check savedInstanceState and check if a tagged fragment had already been created... if so reuse the same fragment instead of creating a new one.
as workaround you could clear the menu, before inflating it again, calling clear
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.clear();
getMenuInflater().inflate(R.menu.menu_roi_result_calc, menu);
return true;
}
it removes all entries from the menu, leaving it as it had just been created
When you rotate your application your activity is destroyed and a new one is created. If you are attaching your fragment to the activity where it is being created than it will have the old one attached and will attach a new one. To avoid this I would do something like below. This will remove all of the current fragments and host whatever yours is.
FragmentManager fm = new FragmentManager();
for(Fragment aFrag : fm.getFragments()) {
fm.beginTransaction().remove(aFrag).commit();
}
fragment = createFragment(new Fragment());
fm.beginTransaction().add(R.id.YouGetThePicture, fragment).commit();
My menu has a item to Log in, but when you are logged in I want it to say Log out.
How?
If I'm going to change the item after its created, its probably through this method
#Override
public boolean onCreateOptionsMenu( Menu menu ) {
MenuInflater inflater = getMenuInflater();
inflater.inflate( R.menu.menu_main, menu );
return true;
}
Afaik the onCreateOptionsMenu() happens after the onCreate so putting any getItemId() for the menu there will give me a NullPointerException right away.
I want the app to find out if its supposed to use the string R.string.Logout if its logged in.
I dont even know what to search for for this issue. All I found was how to make a string implement names, like this answer https://stackoverflow.com/a/7646689/3064486
You should use onPrepareOptionsMenu(Menu menu) instead to update menu items
#Override
public boolean onPrepareOptionsMenu(Menu menu){
super.onPrepareOptionsMenu(menu);
MenuItem someMenuItem = menu.findItem(R.id.some_menu_item);
someMenuItem.setTitle("Log out");
return super.onPrepareOptionsMenu(menu);
}
To refresh Menu items call invalidateOptionsMenu();from Activity
From Android API guides: "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.)"
After you inflate a menu, you can customize its items. To get each one, you must call findItem() with the item's id. In particular, you can use setTitle() to change the displayed string.
For example:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
if (mIsLoggedIn)
menu.findItem(R.id.action_login).setTitle("Log out");
return true;
}
where action_login is the id you set for this particular menu item in the menu's xml file.
private void updateUI() {
runOnUiThread(new Runnable() {
#Override
public void run() {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
Menu menu = navigationView.getMenu();
MenuItem nav_signin = menu.findItem(R.id.nav_signin);
nav_signin.setTitle(MyApp.signedIn ? "Sign out" : "Sign in");
}
});
}
In some methods of my Activity I want to check the title of menu or know if it is checked or not. How can I get Activity's menu. I need something like this.getMenu()
Be wary of invalidateOptionsMenu(). It recreates the entire menu. This has a lot of overhead and will reset embedded components like the SearchView. It took me quite a while to track down why my SearchView would "randomly" close.
I ended up capturing the menu as posted by Dark and then call onPrepareOptionsMenu(Menu) as necessary. This met my requirement without an nasty side effects. Gotcha: Make sure to do a null check in case you call onPrepareOptionsMenu() before the menu is created. I did this as below:
private Menu mOptionsMenu;
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
mOptionsMenu = menu
...
}
private void updateOptionsMenu() {
if (mOptionsMenu != null) {
onPrepareOptionsMenu(mOptionsMenu);
}
}
Call invalidateOptionsMenu() instead of passing menu object around.
you could do it by passing the Menu object to your Activity class
public class MainActivity extends Activity
{
...
...
private Menu _menu = null;
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
_menu = menu;
return true;
}
private Menu getMenu()
{
//use it like this
return _menu;
}
}
There several callback methods that provide menu as a parameter.
You might wanna manipulate it there.
For example:
onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
onCreateOptionsMenu(Menu menu)
onCreatePanelMenu(int featureId, Menu menu)
There several more, best you take a look in activity documentation and look for your desired method:
http://developer.android.com/reference/android/app/Activity.html
As far as I could understand what you want here is which may help you:
1. Refer this tutorial over option menu.
2. Every time user presses menu button you can check it's title thru getTitle().
3. Or if you want to know the last menu item checked or selected when user has not pressed the menu button then you need to store the preferences when user presses.
Android now has the Toolbar widget which was a Menu you can set/get. Set the Toolbar in your Activity with some variation of setSupportActionBar(Toolbar) for stuff like onCreateOptionsMenu from a Fragment for example. Thread revived!