How to hide icons from ActionBar? - android

I'm looking to hide a icons from the ActionBar depending on variables. Is there a simple way to do this?
Will I need to use onPrepareOptionsMenu() and if so how?

To hide menu items you should use the setVisible() method on your menu item inside your activity onPrepareOptionsMenu() override after your menu has been inflated. For example:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.example, menu);
if(showItem) {
menu.findItem(R.id.icon).setVisible(true);
} else {
menu.findItem(R.id.icon).setVisible(false);
}
return true;
}
If you have declared your variable inside onCreate(), it will be limited to the scope of onCreate() and therefore inaccessible inside onPrepareOptionsMenu().
For example, instead of this:
#Override
protected void onCreate(Bundle savedInstanceState) {
boolean showItem = false;
// ...
}
Declare it like this:
public boolean showItem = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
}
Also if you want to change the visibility on button press for example, you will need to call the invalidateOptionsMenu() method to reload the menu.

You need to call invalidateOptionsMenu() depending on your variable.
When you call invalidateOptionsMenu() the onPrepareOptionsMenu will be called , where you can hide/show the option menu like this..
#Override
public boolean onPrepareOptionsMenu(Menu menu){
for(int index = 0 ; index < menu.size() ; index ++){
MenuItem menuItem = menu.getItem(index);
if(menuItem != null) {
// hide the menu items
menuItem.setVisible(false);
}
}
return super.onPrepareOptionsMenu(menu);
}

Related

How to hide menu item from fragment?

I want to hide a menuitem from my Menu in my Navigation Drawer.
I tried using setHasOptionsMenu(true) and then adding the method
public boolean onPrepareOptionsMenu(Menu menu){
//this is where i tried to hide the item
menu.findItem(R.id.item).setVisible(false);
}
But it says that is null.
Any suggestions?
You should call setHasOptionsMenu(true) in your fragment's onCreate() method to allow your fragment to handle menu items. So you could do something like this in your fragment:
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
And then, you can override onPrepareOptionsMenu method in your fragment:
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// You can hide the state of the menu item here if you call getActivity().supportInvalidateOptionsMenu(); somewhere in your code
MenuItem menuItem = menu.findItem(R.id.item);
menuItem.setVisible(false);
}
getActivity().invalidateOptionsMenu(); will call onPrepareOptionsMenu and update your menus.
I was also getting the same problem, if you are using Navigation Drawer and want to play with menu then you have to check the fragment visibility:
Please follow the steps in your Fragment, it worked for me:
1)check for the fragment visibility
boolean isMenuVisible = false;
#Override
public void setMenuVisibility(boolean menuVisible) {
try {
super.setMenuVisibility(menuVisible);
if (menuVisible && searchView != null) {
isMenuVisible = menuVisible;
}
} catch (Exception e) {
CommonUtils.firebaseCrashReport(e);
}
}
2)put this code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
2 then just check true value for isMenuVisible and play with menu
#Override public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if(isMenuVisible){
MenuItem menuItem = menu.findItem(R.id.item);
menuItem.setVisible(false);
}
}
This can be done with hiding menu item
In activity:
navigationView = (NavigationView) findViewById(R.id.nav_view);`
In fragment:
Menu nav_Menu = context.navigationView.getMenu();<br/>
nav_Menu.findItem(R.id.item_id).setVisible(false);<br>
you can pass the activity Context to fragment
As you are using a navigation drawer, you have to get MenuItem from it.
Store the NavigationView reference in onCreate :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layoutId);
...
nvDrawer = (NavigationView) findViewById(R.id.nvView);
}
Hide the MenuItem in onPrepareOptionsMenu :
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean ret = super.onPrepareOptionsMenu(menu);
MenuItem stateBtn = nvDrawer.getMenu().findItem(R.id.item);
stateBtn.setVisible(true);
return ret;
}
In onCreate() call
setHasOptionMenu(true)
and check for the null item in onPrepareOptionsMenu() like so..
#Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item=menu.findItem(R.id.menu_id);
if(item!=null)
item.setVisible(false);
}

How do you "deflate" menus in android?

I have a contextual action bar, where I have a setting called "DELETE". When I press that button I want the CAB menu to disappear.
class MyActionModeCallBack implements android.view.ActionMode.Callback {
#Override
public boolean onCreateActionMode(android.view.ActionMode actionMode, Menu menu) {
actionMode.getMenuInflater().inflate(R.menu.event_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(android.view.ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(android.view.ActionMode actionMode, MenuItem menuItem) {
int id = menuItem.getItemId();
if (id == R.id.delete) {
*******
_root.removeView(view);
// This is where I want to remove the CAB menu
*******
}
return false;
}
#Override
public void onDestroyActionMode(android.view.ActionMode actionMode) {
((RelativeLayout)view).removeAllViews();
view.setBackgroundColor(0xFF00FF00);
view.setTag(R.string.viewSelected, "0");
}
}
I was thinking about calling the onDestroyActionMode() right after the _root.removeView(view);, but I don't know what arguments to pass in.
Any suggestions are appreciated, thanks!
If you are trying to hide the item being selected, you can call
menuItem.setVisible(false);
Alternatively, if you want to remove all items from the menu, you can call
optionsMenu.clear();
in the onActionItemClicked() method.
You can save your menu to a field in your onCreateOptionsMenu method as follows:
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
optionsMenu = menu
}
Call actionMode.finish(). This will invoke the onDestroyActionMode() callback.

Menu in fragments

I have this scenario:
I have a activity, lets call itAcitivty1 with
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
I open a fragment from Activity1 lets call it Fragment1 with:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.layout, container, false);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (menu != null){
menu.clear();
}
if (!boolean) {
inflater.inflate(R.menu.menu1, menu);
} else {
inflater.inflate(R.menu.menu2, menu);
}
}
This fragment will be called again from activity as a new instance.
Based on the boolean in onCreateOptionsMenu() I'm deciding what menu should be loaded in the fragment so, during the second instance if I click on a menu item, I see the objects of first instance fragment.
I have no clue, why is this happening?
How is the workflow for displaying menu options...
if (menu != null){
menu.clear();
}
That piece of code might be the root cause.
You're telling the system to clear the menu if it's null. Well, FYI, the menu will never be null in the first place; it is supplied by the system. It might have no items inside, but it'll never be null.
One way to check if a menu already contains an item (or more) is to call hasVisibleItems().
From the documentations:
public abstract boolean hasVisibleItems()
Returns True if there is one or more item visible, else false.
Therefore, this is how you should do it:
if (menu.hasVisibleItems()){
menu.clear();
}
In a case like this, you need to put the menu in activity and update the menu dynamically in onPrepareOptionsMenu()
You need to inflate menu in onCreateOptionsMenu(..) of your Activity1 and need to make return true to display menu.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Your code here
getMenuInflater().inflate(R.menu.main1, menu);//My menu
return true;
}
After that you get menu in your fragment also.
Edits:
If you use single menu file and show / hide MenuItem of your menu. it will solve your problem.
Add all menu in single file.by default all menu items are visible false using android:visible="false"
See example code:
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
MenuItem item1 = menu.getItem(0);
MenuItem item2 = menu.getItem(1);
MenuItem item3 = menu.getItem(2);
MenuItem item4 = menu.getItem(3);
if(!boolean){
//visible items which you want to show when boolean is false
item1.setVisible(true);
item2.setVisible(true);
}
else
{
//visible items which you want to show when boolean is true
item3.setVisible(true);
item4.setVisible(true);
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menuItem1) {
return true;
}
if (id == R.id.menuItem2) {
return true;
}
...
return super.onOptionsItemSelected(item);
}

Android - How to hide menu option for current fragment

I have an ActionBar activity with a FrameLayout and a menu. when the user clicks the menu item I replace the fragment with the relevant new fragment. However, I cannot see an obvious way to remove the menu item for the selected fragment.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
StudyFragment startFragment = new StudyFragment();
startFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add
(R.id.container, startFragment).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_study:
replaceFragment((Fragment)new StudyFragment());
break;
case R.id.action_list:
replaceFragment((Fragment)new ListFragment());
break;
// etc
}
return super.onOptionsItemSelected(item);
}
private void replaceFragment(Fragment f) {
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, f);
transaction.addToBackStack(null);
transaction.commit();
}
The Google documentation on changing menus says to disable the menu in onPrepareOptionsMenu - but how will I know which item has been selected?
--Solution Implemented--
Using Muhammed Refaat's solution below I added two new members to the class:
private Menu activityMenu;
private MenuItem curMenuItem;
Set them in onCreateOptionsMenu
activityMenu = menu;
curMenuItem = activityMenu.findItem(R.id.action_study);
curMenuItem.setVisible(false);
And changed them on onOptionsItemSelected
curMenuItem.setVisible(true);
curMenuItem = activityMenu.findItem(id);
curMenuItem.setVisible(false);
First get the item you want to remove :
MenuItem item = menu.findItem(R.id.your_action);
then set it's Visibility false :
item.setVisible(false);
and if the problem is in getting the menu (as it's not in the fragment), you can easily get a context from the activity that contains the menu and get the menu by it.
Inside your fragment you will have to use setHasOptionsMenu(true); in order to access options menu from within your fragment.
Code (inside your second fragment where you wanna hide the item):
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO your code to hide item here
super.onCreateOptionsMenu(menu, inflater);
}
Similarly, for your fragment where you want to show that MenuItem you can do the similar thing.
In the fragment where you want to hide the Item
#Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item=menu.findItem(R.id.action_search);
item.setVisible(false);
and in onCreate() of your fragment
setHasOptionsMenu(true);
Adding to Muhammed's answer above. Once the item has been set as invisible, you may need to also disable the item. Note Google's comment: "Even if a menu item is not visible, it may still be invoked via its shortcut (to completely disable an item, set it to invisible and disabled)" under setVisible() in the MenuItem documentation.
Thus:
item.setVisible(false);
item.setEnabled (false);
Add below codes into your fragment
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem item = menu.findItem(R.id.save);
item.setVisible(false);
}
// create Boolean variable in the main activity
private var menuvisibile: Boolean = true
// while navigating fragments set the menuvisibile value and use it
// variable as part of the return statement
invalidateOptionsMenu()
menuvisibile = false
override fun onCreateOptionsMenu(menu: Menu?): Boolean
{
val menuInflater = menuInflater
menuInflater.inflate(R.menu.notification,menu)
return menuvisibile
}
working well for me.

Hide MenuItem in some Fragments

I using menu drawer which has more Fragments. In some Fragments I have menu item REFRESH but in some fragments I want hide this menu item (I don't want show menu but I don't want hide ActionBar).
I try add override onCreateOptionsMenu() to Fragment where I don't want show this menu item but I can not get it to work. I try many way see commented line in code. Does any idea where is problem? And last this menu item go to hide when I activate menu drawer when is called onPrepareOptionsMenu() in MainActivity but I need do this when I'm in Fragment.
Fragment where I want hide menu item REFRESH:
public class FindPeopleFragment extends Fragment {
public FindPeopleFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_find_people, container, false);
//setHasOptionsMenu(false);
return rootView;
}
private Menu menu=null;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
inflater.inflate(R.menu.main, menu);
this.menu=menu;
menu.findItem(R.id.refresh).setVisible(false);
getActivity().invalidateOptionsMenu();
//setHasOptionsMenu(false);
super.onCreateOptionsMenu(menu,inflater);
}
}
MainActivity where is defined MENU DRAWER:
//Slide menu item click listener
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.refresh:
Toast.makeText(this, "Refreshing data...", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
// Called when invalidateOptionsMenu() is triggered
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.refresh).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
In the fragment where you want to hide the Item
#Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item=menu.findItem(R.id.action_search);
if(item!=null)
item.setVisible(false);
}
and in onCreate() of your fragment
setHasOptionsMenu(true);
In the Fragment where you don't want to show any menu options, you need setHasOptionsMenu(false); in the onCreate(), like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
However, the menu that is being shown that you would like to hide (REFRESH), belongs to MainActivity. That is why it is always shown. Since you want to control the menu at the Fragment level (and not show an Activity options menu), my suggestion is to delete the menu code from the Activity and implement it in your Fragment.
Activitys and Fragments can each have their own separate menus. See this link.
please try this
#Override
public void onPrepareOptionsMenu(Menu menu) {
menu.clear();
}
and put this on your fragmen's onCreate()
setHasOptionsMenu(true);
In Fragment Class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
}
in Kotlin for those who needs it
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
menu.clear()
}
I used the code below for hiding menu items in a fragment where I don't want to use it.
Note: Please read comment
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
Fragment whichFragment=getVisibleFragment();//getVisible method return current visible fragment
String shareVisible=whichFragment.getClass().toString();
if(shareVisible.equals(AccFragment.class.toString())
||shareVisible.equals(SocFragment.class.toString())
||shareVisible.equals(DevFragment.class.toString())
){
MenuItem item=menu.findItem(R.id.action_share);
item.setVisible(false);
}
return super.onCreateOptionsMenu(menu);
}
in Kotlin
override fun onPrepareOptionsMenu(menu: Menu) {
val item: MenuItem = menu.findItem(R.id.action_search)
item.isVisible = false
}
in onCreate() of your fragment
setHasOptionsMenu(true)
There are many different versions of similar solutions but unfortunately, none of them worked for me. I am sharing what eventually was useful for me to hide the whole overflow menu with multiple menu items. Thought maybe it's useful for anyone.
I grouped my menus with an id and then referred that id
#Override
public void onPrepareOptionsMenu(Menu menu) {
menu.setGroupVisible(R.id.menu_overflow, false);
super.onPrepareOptionsMenu(menu);
}
If you want to hide any individual menu item then you can use
menu.getItem(R.id.action_licenses).setVisible(false);
Important thing is that you should have setOptionsMenu(true) in onViewCreated()
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
Call setHasOptionMenu(true) in onCreateView()
and Do not call super.onCreateOptionsMenu() in fragment's onCreateOptionMenu() instead call menu.clear() because this will override the existing menu with the activity's menu
This worked in my case.
Or solve it in the same Fragment which created the menu, if you host the Actionbar on Activity level. This way you don't have to add it on every other Fragment where you don't want to show it:
public override void OnDestroy()
{
base.OnDestroy();
HasOptionsMenu = false;
}
Add these functions to your Fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item=menu.findItem(R.id.delete);
item.setVisible(false);
}
Firstly in your Activity that has the toolbar, create a method that sets up the overflow menu for you:
public void setUpOptionMenu(Toolbar toolbar){
this.setSupportActionBar(toolbar);
}
In your fragments onCreateView() method, get the reference of your current activity and call your activities setUpOptionMenu() method:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
...
...
public void ((YourActivityName)this.getActivity()).setUpOptionMenu(null);
...
...
}
Cheers!!!
Overrride the following method just in your fragment and it will do the trick.
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
// Do something that differs the Activity's menu here
getActivity().getMenuInflater().inflate(R.menu.drawer, menu);
}
2022 KOTLIN
On your activity, where you navigate to fragments, You can try like below, On below code, Tested on Side Navigation view, It has been shown wherever needed using toolbar.inflateMenu(R.menu.toolbar_menu) and hidden using toolbar.menu.clear() on toolbar reference.
binding.naviSideNav.setNavigationItemSelectedListener(NavigationView.OnNavigationItemSelectedListener {
when (it.itemId) {
R.id.side_nav_home->{
toolbar.title=""
toolbar.menu.clear()
toolbar.inflateMenu(R.menu.toolbar_menu)
toolbar.setBackgroundColor(ContextCompat.getColor(this,R.color.home_screen_bg))
navController.navigate(R.id.navigation_home)
}
R.id.side_nav_appointments->{
}
R.id.side_nav_ehr->{
}
R.id.side_nav_invoices->{
}
R.id.side_nav_settings->{
toolbar.title=getString(R.string.nav_menu_Settings)
toolbar.menu.clear()
toolbar.setBackgroundColor(ContextCompat.getColor(this,R.color.home_screen_bg))
navController.navigate(R.id.navigation_settings)
}
R.id.side_nav_logout->{
}
}
binding.dlt.closeDrawer(GravityCompat.START)
true
})
Clean and redraw menu item
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
menu.clear()
inflater.inflate(R.menu.main_menu, menu)
menu.findItem(R.id.id_menu_search)?.isVisible = true
super.onCreateOptionsMenu(menu, inflater)
}
I have checked the answers but now the optionMenu has been deprecated in the latest Android api level
setHasOptionsMenu(false)
so for the people who are using MenuProvider for optionMenu can use the
setMenuVisibility(false)
like this in fragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setMenuVisibility(false)
}
Just find the item you want to hide using findItem then set its visibility to false.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.action_settings);
item.setVisible(false);
}

Categories

Resources