hide/show options menu when clicking buttons - android

I'm using some buttons in my fragments. When i checks those buttons then options menu should display. And when i uncheck it it should hide options menu. How should i do this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mLocation = getArguments().getString(Beco.EXTRA_LOCATION);
listMalls = temporaryModelCache.getDealData().getFacets().getArea();
listCategories = temporaryModelCache.getDealData().getFacets().getCategories();
listGender = temporaryModelCache.getDealData().getFacets().getAgeGroup();
try {
MainActivity activity = (MainActivity) getActivity();
if (activity != null) activity.hideBottomBar();
} catch (Exception ignored) {
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.forgot_password, menu);
mResetButton = menu.findItem(R.id.action_reset);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.action_reset:
Log.d(TAG, "onClick");
resetFilter();
return true;
}
return super.onOptionsItemSelected(item);
}
And this is the event that i need to hide/display options menu
private void checkSelected() {
if (!mapMall.isEmpty() || !mapGender.isEmpty() || !mapCategory.isEmpty()) {
footerTab.setVisibility(View.VISIBLE);
} else {
footerTab.setVisibility(View.GONE);
}
}
When if (!mapMall.isEmpty() || !mapGender.isEmpty() || !mapCategory.isEmpty()) i need to display actions menu and in the else part i need to hide options menu ! How can i achieve this?

call invalidateOptionsMenu() for hide and show option menu
Boolean Isreset= false;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.forgot_password, menu);
mResetButton = menu.findItem(R.id.action_reset);
if(!Isreset)
{
mResetButton.setVisibility(true);
}else{
mResetButton.setVisibility(false);
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.action_reset:
Log.d(TAG, "onClick");
resetFilter();
Isreset= true;
invalidateOptionsMenu();
return true;
}
return super.onOptionsItemSelected(item);
}

You can keep the instance of Menu object and later on use it to invalidate the options menu.
private Menu menu;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mLocation = getArguments().getString(Beco.EXTRA_LOCATION);
listMalls = temporaryModelCache.getDealData().getFacets().getArea();
listCategories = temporaryModelCache.getDealData().getFacets().getCategories();
listGender = temporaryModelCache.getDealData().getFacets().getAgeGroup();
try {
MainActivity activity = (MainActivity) getActivity();
if (activity != null) activity.hideBottomBar();
} catch (Exception ignored) {
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.forgot_password, menu);
mResetButton = menu.findItem(R.id.action_reset);
this.menu = menu;
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.action_reset:
Log.d(TAG, "onClick");
resetFilter();
return true;
}
return super.onOptionsItemSelected(item);
}
Using the menu object then toggle the options menu.
private void checkSelected() {
if (!mapMall.isEmpty() || !mapGender.isEmpty() || !mapCategory.isEmpty()) {
footerTab.setVisibility(View.VISIBLE);
menu.findItem(R.id.action_reset).setVisibility(View.VISIBLE);
} else {
footerTab.setVisibility(View.GONE);
menu.findItem(R.id.action_reset).setVisibility(View.GONE);
}
}

Related

How to set visibility of one menu item false after clicking on another menu item

I am trying to set visibility of SaveMessage true after clicking on UnsaveMessage and visibility of Unsavemessage false but i only see on item and nothing happens on Onclick
My code
private boolean isEditing = true;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_message,menu);
menu.findItem(R.id.UnsavedMessage).setVisible(isEditing);
menu.findItem(R.id.SaveMessage).setVisible(!isEditing);
return super.onCreateOptionsMenu(menu);
}
#Override
public void supportInvalidateOptionsMenu() {
super.supportInvalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == R.id.UnsavedMessage){
isEditing=false;
}
if (item.getItemId()==R.id.SaveMessage){
isEditing=true;
}
return true;
}
You need to do this
private boolean isEditing = true;
private MenuItem unSavedMsg;
private MenuItem SaveMsg;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_message,menu);
unSavedMsg = menu.findItem(R.id.UnsavedMessage)
unSavedMsg .setVisible(isEditing);
saveMsg = menu.findItem(R.id.SaveMessage)
saveMsg .setVisible(!isEditing);
return super.onCreateOptionsMenu(menu);
}
#Override
public void supportInvalidateOptionsMenu() {
super.supportInvalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == R.id.UnsavedMessage){
isEditing=false;
// Show/Hide Btn here
unSavedMsg.setVisibility(false)
saveMsg.setVisibility(true)
}
if (item.getItemId()==R.id.SaveMessage){
isEditing=true;
// Show/Hide Btn here
unSavedMsg.setVisibility(true)
saveMsg.setVisibility(false)
}
return true;
}

Menu items in one Fragment - Getting mixed up with other Fragment's menu items

I have an Activity with DrawerLayout and a RelativeLayout (with ViewPager and a FrameLayout as children for it) and a ListView as children. I am loading a Fragment inside the FrameLayout when an item in the menu inside DrawerLayout is clicked.
The ViewPager loads 3 Fragments. Each of the Fragment has a menu with 3 items. The Fragment that is loaded inside the FrameLayout has menu with 2 items.
The problem is, when i switch between ViewPager and the FrameLayout's Fragment, the menu items are getting added up, to each other.
Please refer the screenshots below..
I am guessing, that i am doing something wrong in onCreateOptionsMenu, onOptionsItemSelected or onPrepareOptionsMenu methods.
Activity's Methods:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerLeft)) {
mDrawerLayout.closeDrawer(mDrawerLeft);
} else {
mDrawerLayout.openDrawer(mDrawerLeft);
}
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
One of the ViewPager's Fragment: Other two are also similar:
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_all, menu);
SearchManager searchManager = (SearchManager) activity.
getSystemService(Context.SEARCH_SERVICE);
searchMenuItem = menu.findItem(R.id.ic_action_search);
searchView = (SearchView) searchMenuItem.getActionView();
searchView.setSearchableInfo(searchManager.
getSearchableInfo(activity.getComponentName()));
searchView.setOnQueryTextListener(this);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_list) {
prefs.edit().putString(Const.VIEWPAGER.VIEW_TYPE, Const.VIEWPAGER.LIST_VIEW).apply();
mStaggeredLayoutManager.setSpanCount(1);
} else if (item.getItemId() == R.id.action_grid) {
prefs.edit().putString(Const.VIEWPAGER.VIEW_TYPE, Const.VIEWPAGER.GRID_VIEW).apply();
mStaggeredLayoutManager.setSpanCount(2);
} else if (item.getItemId() == R.id.action_mini) {
prefs.edit().putString(Const.VIEWPAGER.VIEW_TYPE, Const.VIEWPAGER.MINI_VIEW).apply();
mStaggeredLayoutManager.setSpanCount(1);
}
ActivityCompat.invalidateOptionsMenu(activity);
mViewPagerPetitionsRecyclerViewAdapter.notifyDataSetChanged();
mIMainAllPetitionsListener.onLayoutChangedListener();
return super.onOptionsItemSelected(item);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem list_item = menu.findItem(R.id.action_list);
MenuItem grid_item = menu.findItem(R.id.action_grid);
MenuItem mini_item = menu.findItem(R.id.action_mini);
String item_type = prefs.getString(Const.VIEWPAGER.VIEW_TYPE, Const.VIEWPAGER.LIST_VIEW);
if (item_type.equalsIgnoreCase(Const.VIEWPAGER.LIST_VIEW)) {
list_item.setChecked(true);
grid_item.setChecked(false);
mini_item.setChecked(false);
} else if (item_type.equalsIgnoreCase(Const.VIEWPAGER.GRID_VIEW)) {
list_item.setChecked(false);
grid_item.setChecked(true);
mini_item.setChecked(false);
} else if (item_type.equalsIgnoreCase(Const.VIEWPAGER.MINI_VIEW)) {
list_item.setChecked(false);
grid_item.setChecked(false);
mini_item.setChecked(true);
}
}
FrameLayout's Fragment:
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_id_card, menu);
MenuItem menuItem = menu.findItem(R.id.edit);
menuItem.setVisible(false);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_share) {
shareIDCard();
} else if (id == R.id.action_save_as_image) {
saveAsImage();
} else if (id == R.id.action_save_as_wallpaper) {
SaveAsWallPaper();
} else if (id == R.id.edit) {
setEnabled(true);
isEditable = true;
ActivityCompat.invalidateOptionsMenu(activity);
} else if (item.getItemId() == R.id.save) {
....
ActivityCompat.invalidateOptionsMenu(activity);
} else if (item.getItemId() == R.id.cancel) {
...
ActivityCompat.invalidateOptionsMenu(activity);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem menuItemEdit = menu.findItem(R.id.edit);
MenuItem menuItemSave = menu.findItem(R.id.save);
MenuItem menuItemCancel = menu.findItem(R.id.cancel);
....
menuItemEdit.setVisible(false);
menuItemSave.setVisible(false);
menuItemCancel.setVisible(false);
}
Can someone help me understand why is this happening and what can i do to fix this?
Add menu.clear(); in your onCreateOptionsMenu before inflate

How to click disabled option menu item in Toolbar android?

I have two option items in a Toolbar. When one item is clicked, that item will be enabled. Then another item must be disabled. But, once the item was disabled I can't fire click event anymore on that item. Is there anyway that I can click on the disable item?
Thank you
I did like this but its not working anymore
MenuItem tureMenuItem;
MenuItem dingMenuItem
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
getActivity().getMenuInflater().inflate(R.menu.lore_fragment, menu);
tureMenuItem = menu.findItem(R.id.menu_ture);
dingMenuItem = menu.findItem(R.id.menu_ding);
tureMenuItem.setEnabled(true);
dingMenuItem.setEnabled(false);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_ding:
tureMenuItem.setEnabled(true);
dingMenuItem.setEnabled(false);
break;
case R.id.menu_ture:
tureMenuItem.setEnabled(false);
dingMenuItem.setEnabled(true);
break;
}
return super.onOptionsItemSelected(item);
}
Using setEnabled() will work. manage with your conditions.
you must be doing some action on those menu items right. You can enable the other item at the end of action.since you have not posted I have only option. Using Handler.PostDelayed.
boolean isMenuEnabled;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_settings) {
this.isMenuEnabled = true;
tureMenuItem.setEnabled(true);
dingMenuItem.setEnabled(false);
handler.postDelayed(runnable,1000);
return true;
}
else if(item.getItemId()== R.id.action_settings1) {
this.isMenuEnabled = true;
tureMenuItem.setEnabled(false);
dingMenuItem.setEnabled(true);
handler.postDelayed(runnable,1000);
return true;
}
return super.onOptionsItemSelected(item);
}
remove the callbacks
#Override
protected void onDestroy() {
handler.removeCallbacks(runnable);
super.onDestroy();
}
runnable with delay
Runnable runnable = new Runnable() {
#Override
public void run() {
if(isMenuEnabled){
tureMenuItem.setEnabled(true);
dingMenuItem.setEnabled(true);
isMenuEnabled=false;
}
}
};
You need to check below example code to disable and enable menu item vice-versa.
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
if(menu.getItem(0))
{
menu.getItem(0).setEnable(false);
menu.getItem(1).setEnable(true);
}
else if(menu.getItem(1))
{
menu.getItem(1).setEnable(false);
menu.getItem(0).setEnable(true);
}
return super.onPrepareOptionsMenu(menu);
}

Android ActionBar Action Items

I am using Actionbar Sherlock and and i have three buttons
Search with a SearchView
Categories which opens a Dialog Fragment
Sort which opens a hiddent drop down menu
When i click the Search Button the SearchView text expands. When the Search view has expanded i want to hide all the other icons from the action bar and it should return when i exit the expanded searchView mode.
public class MainActivity extends SherlockFragmentActivity implements
SearchView.OnQueryTextListener {
protected static CharSequence[] _categories = { "Amusement Park",
"Bird Sanctuary", "Wild Life", "River", "Hill Station", "Temple" };
protected static boolean[] _selections = new boolean[_categories.length];
public SearchView mSearchView;
private TextView mStatusView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
MenuItem categoryItem = menu.findItem(R.id.action_category);
MenuItem sortItem = menu.findItem(R.id.action_sort);
mSearchView = (SearchView) searchItem.getActionView();
setupSearchView(searchItem, categoryItem, sortItem);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
/*
* case R.id.action_go: Intent i = new Intent(MainActivity.this,
* PlaceActivity.class); startActivity(i); break;
*/
/*
* case R.id.action_search: Toast.makeText(this, "Searh",
* Toast.LENGTH_LONG).show(); break;
*/
case R.id.action_category:
showDialog();
break;
case R.id.action_sort_alpha_az:
Toast.makeText(this, "Alpha AZ", Toast.LENGTH_LONG).show();
break;
case R.id.action_sort_alpha_za:
Toast.makeText(this, "Alpha ZA", Toast.LENGTH_LONG).show();
break;
case R.id.action_sort_dist_nf:
Toast.makeText(this, "Dist NF", Toast.LENGTH_LONG).show();
break;
case R.id.action_sort_dist_fn:
Toast.makeText(this, "Dist FN", Toast.LENGTH_LONG).show();
break;
default:
// return super.onOptionsItemSelected(item);
break;
}
return true;
}
private void setupSearchView(MenuItem searchItem, MenuItem categoryItem,
MenuItem sortItem) {
mSearchView.setIconifiedByDefault(true);
searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
}
public boolean onQueryTextChange(String newText) {
Log.i("Nomad", "onQueryTextChange");
return false;
}
public boolean onQueryTextSubmit(String query) {
Log.i("Nomad", "onQueryTextSubmit");
return false;
}
public boolean onClose() {
Log.i("Nomad", "onClose");
return false;
}
protected boolean isAlwaysExpanded() {
return false;
}
}
I'm doing the same as follows:
private Menu mainMenu = null;
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
mainMenu = menu;
MenuItem searchItem = menu.findItem(R.id.action_search);
MenuItem categoryItem = menu.findItem(R.id.action_category);
MenuItem sortItem = menu.findItem(R.id.action_sort);
mSearchView = (SearchView) searchItem.getActionView();
mSearchView.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//hide action item
if (mainMenu != null)
mainMenu.findItem(R.id.quick_actions).setVisible(false);
}
});
mSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
//re-show the action button
if (mainMenu != null)
mainMenu.findItem(R.id.quick_actions).setVisible(true);
return false;
}
});
//setupSearchView(searchItem, categoryItem, sortItem);
return true;
}
My solution is:
#Override
public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater)
{
final MenuItem item = menu.add(0, MENU_SEARCH, 0, "Search");
final SearchView searchView = new SearchView(getActivity());
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener()
{
#Override
public void onFocusChange(View view, boolean queryTextFocused)
{
if(!queryTextFocused)
{
item.collapseActionView();
}
int count = menu.size();
for (int i = 0; i < count; i ++)
{
MenuItem it = menu.getItem(i);
it.setVisible(item.equals(it)) || !queryTextFocused);
}
}
});
item.setActionView(searchView);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
}
Simply on the xml of menu, just give the attribute as app:showAsAction="collapseActionView|ifRoom" for seachview and to other menu items give it as app:showAsAction="ifRoom".This will give you the expected result.

onOptionsItemSelected not called when using actionLayout (SherlockActionBar)

The method onOptionsItemSelected isn't being called when using actionLayout in a menu item.
Am I missing something, or is it a known problem with SherlockActionBar?
Activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.article, menu);
super.onCreateOptionsMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "onOptionsItemSelected()");
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.menu_item_comment:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Menu
<item android:id="#+id/menu_item_comment"
android:showAsAction="ifRoom"
android:actionLayout="#layout/action_bar_comment_layout"/>
well, you have to set onClickListener on that actionLayout to receive callback. I do it like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.map_menu, menu);
for (int i = 0; i < menu.size(); i++) {
MenuItem item = menu.getItem(i);
if (item.getItemId() == R.id.menu_more) {
itemChooser = item.getActionView();
if (itemChooser != null) {
itemChooser.setOnClickListener(this);
}
}
}
return super.onCreateOptionsMenu(menu);
}
You'll have to add your own OnClickListener and explicitly call onOptionsItemSelected:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem awesomeMenuItem = menu.findItem(R.id.action_awesome);
View awesomeActionView = menuItem.getActionView();
awesomeActionView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOptionsItemSelected(awesomeMenuItem));
}
});
}
P.S: Don't know why it doesn't work out of the box.
You should use MenuItemCompat.getActionView(menuItem); instead of item.getActionView(); if you are developing for older version.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
for (int i = 0; i< menu.size() ;i++) {
MenuItem menuItem = menu.getItem(i);
if (menuItem.getItemId() == R.id.add_item) {
View view = MenuItemCompat.getActionView(menuItem);
if (view != null) {
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ToDoActivity.class);
startActivity(intent);
}
});
}
}
}
return true;
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_add_require, menu)
val menuItem = menu!!.findItem(R.id.menu_cart)
val view = menuItem.actionView
view.setOnClickListener {
onOptionsItemSelected(menuItem)
}
return true
}
Working for me (code is in kotlin)
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
View view = menu.findItem(R.id.menu_item_comment).getActionView();
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something
}
});
return true;
}
Also, (and that was very important for me, so other answers did not work) you need to disable the clickable option of all views in your action layout (that is, action_bar_comment_layout.xml):
android:clickable="false"
Combining #Arun Kumar's and #Luten's answers, the below method will make the implementation generic. For all the menu items using actionView, we setOnClickListener to call onOptionsItemSelected(item).
This way we can mix and match normal and actionLayout menu items, without worrying about setting individual onClickListeners.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(menuResourceId(), menu);
for (int i = 0; i < menu.size(); i++) {
final MenuItem item = menu.getItem(i);
View actionView = MenuItemCompat.getActionView(item);
if (actionView != null) {
actionView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
onOptionsItemSelected(item);
}
});
}
}
super.onCreateOptionsMenu(menu, inflater);
}

Categories

Resources