I have an Activity which hosts a ViewPager of Fragments as pages.
The Activity has a single MenuItem which has to be enabled/disabled depending on the Actions in Fragments.
I could have gone with Callbacks, but is there a way to get the MenuItem of the parent Activity in the Fragment?
like: getActvity().getActionBar().getMenuItem(0);
Quoting docs
If you want to update
Your fragments can contribute menu items to the activity's Options
Menu (and, consequently, the Action Bar) by implementing
onCreateOptionsMenu(). In order for this method to receive calls,
however, you must call setHasOptionsMenu() during onCreate(), to
indicate that the fragment would like to add items to the Options Menu
(otherwise, the fragment will not receive a call to
onCreateOptionsMenu()).
So have this in onCreate
setHasOptionsMenu(true);
Override onCreateOptionsMenu()
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
super.onCreateOptionsMenu(menu, inflater);
}
Related
I am having Viewpager with 3 fragments. I want to show menu in only one of the fragments.
1st, I don't know why toolbar.inflateMenu doesn't work.
2nd, the menu works, if I have onPrepareOptionsMenu method and do
getMenuInflater().inflate(R.menu.add_user, menu); but the menu is displayed in all the fragments.
So, according to other questions in stack overflow, I implemented the below code, but it doesn't show the menu, it enters the method but menu is not shown.
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
//getMenuInflater().inflate(R.menu.add_user, menu);
info("Menu=>${tabs_viewpager.currentItem}")
val menuItem = menu?.findItem(R.id.addUserMenu)
menuItem?.setVisible(tabs_viewpager.currentItem == 1)
return true
}
The control comes to this method and shows currentItem. But it doesn't display the menu. Menu is there with id. Can someone direct me what can I correct to get this work?
try calling setHasOptionsMenu(true); in oncreate() of the fragments where you want the menu to show (you can set it to false in the fragments where you do not want the menu to show).
also include:
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// your code
}
in the fragments where you want to set/change the menu. this is called everytime before the menu is shown.
you can also call invalidateOptionsMenu() or supportInvalidateOptionsMenu() (if you're using the support library) to force onPrepareOptionsMenu(menu) to be called.
you may want to check out this menus tutorial
good luck
clive
I want replace current menu of action bar with another when change action bar.
To achieve this I wrote:
getMenuInflater().inflate(R.menu.menu2, menu_bar);
But it add new menu at the rest of current menu.
What i want is remove current and add the new one.
How can I do that?
You can call invalidateOptionsMenu(), which will cause the system to call onPrepareOptionsMenu(Menu menu) again. Inside this method, just check which one of your two menus you should inflate, after calling menu.clear().
Note that invalidateOptionsMenu() has been introduced in API 11 (Honeycomb). If you need to target a lower API level, you can store your Menu object from onPrepareOptionsMenu(Menu menu) as an attribute in your Activity, and directly call clear() on it, then inflate the needed menu as you are already doing.
If you're doing it when changing fragments then:
(1) Create a menu file for fragment
(2) onCreate() method of Fragment set setHasOptionsMenu(true);
(3) Override onCreateOptionsMenu, where you'll inflate the fragment's menu and attach it to your standard menu.
#Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu2, menu);
}
(4) Override onOptionItemSelected in your fragment for item handlers.
Check the link below for more details..
the answer below is correct just has a extra point that will said
You can call invalidateOptionsMenu(), which will cause the system to call onPrepareOptionsMenu(Menu menu) again. Inside this method, just check which one of your two menus you should inflate, after calling menu.clear().
Note that invalidateOptionsMenu() has been introduced in API 11 (Honeycomb). If you need to target a lower API level, you can store your Menu object from onPrepareOptionsMenu(Menu menu) as an attribute in your Activity, and directly call clear() on it, then inflate the needed menu as you are already doing.
point : at onPrepareOptionsMenu(Menu menu) should not call older menu item that lead to Error
public boolean onPrepareOptionsMenu(Menu menu) {
// Error -> menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
menu.clear();
getMenuInflater().inflate(current_menu, menu);
return super.onPrepareOptionsMenu(menu);
}
I have various types of fragment in my application and there are 3 icons on ActionBar (filter, refresh and sort) but I don't want to show all 3 icons in each of the fragments. I have to show only some of them according to the fragment.
Similar thing I want to do with left drawer. On some fragments I want to show left drawer whereas don't want to display left drawer on others.
I have a Activity class in my application on which I am attaching these fragments and currently I am handling these two things in this class and code has become mess with if-else conditions.
So right now I am checking fragment name and then setting action bar icons and left drawer attributes according to it.
Please tell me a better way to do it( preferably to handle this in Fragment itself)
Thanks
Fragments have access to their activity through getActivity() function which will return non-null activity after onAttach() is called (and before onDetach()). Once the fragment has the activity it can tell it to do whatever you were doing right in the activity manually with checks, including changing the action bar buttons.
In order to show the options depending on the fragment, you can simply do the following:
Add setHasOptionsMenu(true) to the onCreate() method of the fragment and tell the Activity to redraw its options menu.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getActivity().invalidateOptionsMenu();
}
Next override the onCreateOptionsMenu() method to inflate the options that you want for your fragment.
// No support library - support library api slightly different
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Add Fragment menu elements to Activity menu elements
inflater.inflate(R.menu.myfragmentmenu, menu);
super.onCreateOptionsMenu(menu,inflater);
}
Finally make sure to capture all option items in the onOptionsItemSelected() method of your activity.
(Important note: make sure to replace fragments instead of adding them. Otherwise onCreateOptionsMenu() will be called for each fragment.)
In order to disable and enable the drawer, you can add the following method to your Activity and call it from your fragment:
public void toggleDrawer(boolean enabled) {
if (enabled) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
mDrawerToggle.setDrawerIndicatorEnabled(true);
} else {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mDrawerToggle.setDrawerIndicatorEnabled(false);
}
}
Create a new project from a sample project called ActionBarCombat and also download this sample application here http://www.learn2crack.com/2014/06/android-sliding-navigation-drawer-example.html
I once combined the two to come up with an application has action bar attributes as well as left drawer
To structure your code a bit why don't you create some methods in your activity like displayRefreshIcon(boolean visible) in which you handle the visibly of these items.
From your fragment you can call these methods (like frangulyan suggests) through the getActivity() function.
If (getActivity() != null && getActivity() instanceof MyActivity) {
((MyActivity)getActivity()).displayRefreshIcon(true);
}
In main thread or usual it is somehow impossible to do make changes in the activity itself, because fragments are separated module who are attached with activities but not the part of them.
But there is a shortcut that is to send message (handler) to activity to update the show the respective actionbar components
(most probably if you are using this fragment only for specific activity).
There you should make a base fragment and each fragment should extend baseFragment and at onResume method you have to check instance of Fragment then according to them you can update actionBar View.
Using any type of fragment, you should just have access to the methods (you have to override them): onCreateOptionsMenu, onPrepareOptionsMenu and onOptionsItemSelected. These methods should provide you with plenty of handles to create a menu per fragment. You could create a menu layout file per fragment and handle them in the method designed to do so. The methods:
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.overviewmenu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
This works just fine but If I'm on a different activity and I use the back button, it won't update the action bar because the activity is already created and it won't update the action bar. Already tried to use supportInvalidateOptionsMenu() on the on_create method but it didn't work.
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
Cursor cursor = messages.getMessages();
if(cursor.getCount()>0){
inflater.inflate(R.menu.actionbar1, menu);
}else{
inflater.inflate(R.menu.actionbar2, menu);
}
return super.onCreateOptionsMenu(menu);
}
As the documentation for onCreateOptionsMenu(Menu) states:
This is only called once, the first time the options menu is
displayed. To update the menu every time it is displayed, see
onPrepareOptionsMenu(Menu).
So going back to an already created Activity does not trigger onCreateOptionsMenu(Menu) again.
What I suggest you to do is create just one menu containing all the menu items and selectively activate/deactivate them in onPrepareOptionsMenu(Menu) based on one or more flags. Then put invalidateOptionsMenu() in onResume() which is called every time the Activity is shown.
Hope it helps
Try calling invalidateOptionsMenu whenever you need to change the icon.
It will destroy your menus and re-inflate them by calling onPrepareOptionsMenu.
I read that it was possible to display a different menu for each tab on this guide.
I have 3 tabs initialized in MainActivity.
Even if I call onPrepareOptionsMenu() or onCreateOptionsMenu() in each included Activity, they are never executed.
I just succeed in displaying a menu on MainActivity's initialization...
MainActivity:
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.menu_tab_1, menu);
return true;
}
This menu is shown.
One of my TabActivities:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.menu_tab_2, menu);
return true;
}
This menu is not refreshed when I change the tab.
But I tried multiple combinations (onCreate / onPrepare, Override...) without success.
How do it properly?
Thanks
You have two options to do this.
First, you can override the onKeyDown method, and detect when the user presses the menu, and instead of letting the main activity handle it, dispatch the event to the active tab activity.
Else, you can use Fragments instead of activities inside your Tab host. The fragment mechanism is great to combine the Options Menus from multiple source (usually one activity and one or more fragments).