how to reload menu android in the same activity? - android

I have a menu in my app android. When I click on add favorites, I need to reload the menu options, making it appear del favorites in the options and not appear add favorites.
I don't want use reload activity because of the back button.
My code:
public boolean onCreateOptionsMenu(Menu menu) {
try
{
MenuItem menuInicio = menu.add(INICIO, INICIO, 0, "InĂ­cio");
menuInicio.setIcon(android.R.drawable.ic_menu_edit);
MenuItem menuBusca = menu.add(BUSCA, BUSCA, 0, "Buscar");
menuBusca.setIcon(android.R.drawable.ic_menu_search);
SubMenu menuFavoritos = menu.addSubMenu(FAVORITOS, FAVORITOS, 0, "Favoritos");
if(!phytoterapicContent.getPhytoterapicItem().getIsFav())
menuFavoritos.add(FAVORITOS, ADD_FAV, 0, "Adicionar aos Favoritos");
else
menuFavoritos.add(FAVORITOS, DEL_FAV, 1, "Remover dos Favoritos");
menuFavoritos.add(FAVORITOS, LIST_FAV, 2, "Listar Favoritos");
menuFavoritos.setIcon(android.R.drawable.star_off);
}
catch (Exception e) {
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case INICIO:
Intent it = new Intent(ShowPhytoterapicActivity.this, HomeActivity.class);
startActivity(it);
break;
case BUSCA:
Intent it3 = new Intent(ShowPhytoterapicActivity.this, ShowSearchParametersActivity.class);
startActivity(it3);
break;
case ADD_FAV:
try {
Dao<PhytoterapicItem, Integer> phytoterapicItemDao = getHelper().getPhytoterapicItemDao();
phytoterapicContent.getPhytoterapicItem().setIsFav(true);
phytoterapicItemDao.update(phytoterapicContent.getPhytoterapicItem());
Toast.makeText(ShowPhytoterapicActivity.this, "Adicionado aos Favoritos", Toast.LENGTH_LONG).show();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case DEL_FAV:
try {
Dao<PhytoterapicItem, Integer> phytoterapicItemDao = getHelper().getPhytoterapicItemDao();
phytoterapicContent.getPhytoterapicItem().setIsFav(false);
phytoterapicItemDao.update(phytoterapicContent.getPhytoterapicItem());
Toast.makeText(ShowPhytoterapicActivity.this, "Removido dos Favoritos", Toast.LENGTH_LONG).show();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case LIST_FAV:
Intent it5 = new Intent(ShowPhytoterapicActivity.this, ShowFavoritesActivity.class);
startActivity(it5);
break;
}
return true;
}
Thanks!

use onPrepareOptionsMenu
Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
if(isChangedStat) {
menu.add(0, MENUITEM, 0, "True");
} else {
menu.add(0, MENUITEM, 0, "False");
}
return super.onPrepareOptionsMenu(menu);
}
Please note two points
1- If possible just enable or disable menu item or looks possible in your case can change the title of same menu will work because menu.clear(); may need over attention while handling
2- as per link provided by Atlos
On Android 2.3.x and lower, the system calls onPrepareOptionsMenu() each time the user opens the options menu (presses the Menu button).
On Android 3.0 and higher, the options menu is considered to always be open when menu items are presented in the action bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().

Here is a relevant link: http://developer.android.com/guide/topics/ui/menus.html#ChangingTheMenu
It depends what version of Android you are targeting. Not sure if you have read this part yet, but any other advice I have would be this verbatim.

Related

Android webview override startActionMode yet keep default dismiss of text selection

After searching for a similar question I gave up and decided to ask myself , if there is an existing answer please notify me.
I have a WebView in which I needed to override the default actionMode , I followed suggestions from many Q & A here and everything was working well until I have noticed that something very specific was missing in the behavior of the actionMode. The dismiss event for the text selection only happens when the user presses "Back button" or "Done" on the action mode. In the Default actionMode when the user presses outside the selected text the actionMode also closes , and this I cannot achieve and not sure how can I acheive it without complicating stuff and writing extra lines of code instead of using the "super" behavior for dissmissing text selection when the user presses outside the selected text.
Hope you can help , thanks ahead.
My WebView with the overriden startActionMode:
#Override
public ActionMode startActionMode(ActionMode.Callback callback) {
/*
* When running Ice Cream Sandwich (4.0) or Jelly Bean (4.1 - 4.3),
* there is a hidden class called 'WebViewClassic' that draws the
* selection. In order to clear the selection, save the callback from
* Classic so it can be destroyed later.
*/
// Check the class name because WebViewClassic.SelectActionModeCallback
// is not public API.
String name = callback.getClass().toString();
if (name.contains("SelectActionModeCallback")) {
webViewDefaultActionModeCallBack = callback;
}
if (mActionMode == null) {
mActionMode = super.startActionMode(mActionModeCallback);
}
return mActionMode;
}
My ActionModeCallback :
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
// Called when the action mode is created; startActionMode() was called
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return true;
}
// Called each time the action mode is shown. Always called after
// onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
// do something
break;
case R.id.item2:
// do something
break;
}
mode.finish();
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
// Semi-hack in order to clear the selection
// when running Android earlier than KitKat.
if (webViewDefaultActionModeCallBack != null) {
webViewDefaultActionModeCallBack.onDestroyActionMode(mode);
}
}
};

Android actionbar menu icon now shown in tablet

I've developed an application which contains a menu icon in my actionbar, I create the menu as below:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
and here's the code for the onOptionsItemSelected:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_home:
startActivity(new Intent(this, MainActivity.class));
return true;
case R.id.menu_adv_search:
startActivity(new Intent(this, AdvSearchActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
using my smart phone the menu icon is there (using LG phone), but when I test it on my tablet (Galaxy Tab 8) the menu icon is gone, but the functionality is still there. pressing the menu soft button at the bottom, the popup appears, but the icon is missing from the top action bar. How to fix it? any ideas?
On devices with hardware menu buttons ( for example Galaxy series of samsung) the overflow menu behaves as the 'traditional' menu, by using the hardware menu button.
please use following attribute for each of your menu item
android:showAsAction="always"
if you are using actionbarcompat pack , then instead of above attribute use following
app:showAsAction="always"
don't forget to add the following namespace aswell
xmlns:app="http://schemas.android.com/apk/res-auto"
As I found out, on devices with menu button hardware provided, the menu icon will be hidden and making the menu item showAsAction="always" will not bring the menu icon back it in my question I was intending to, so I've found the solution Here
and here's the code I've used from the above link to overcome this issue(if it can be called an issue):
private void getOverflowMenu() {
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
you can just put this function in your activity or base activity and call it in your onCreate function and it will do all the magic for ya.

How to add more options to Android default Contextual Action Bar

As we know, by default, after selecting some text on views, android displays Contextual Action Bar (CAB) with some default options, such as: copy, cut, select all...
Now, I want to have an application (that has only 2 options: ON/OFF), If I turn it ON, Some other options will be added to default CAB. If I turn it OFF, my custom options will be removed from Android default CAB.
My question is: Is it possible to Add/Remove some options to this default CAB? How can I make above application?
Thank you!
You'll have to use the setCustomSelectionActionModeCallback on each of your TextViews.
You can have a boolean:
boolean on = true;
Then create a method that actually edits the CAB like so:
private void editContextualActionBar(ActionMode actionMode, Menu menu) {
if (on) {
// adds a new menu item to the CAB
// add(int groupId, int itemId, int order, int titleRes)
menu.add(0, R.id.action_to_be_performed, 1, R.string.action_name);
} else {
// removes the new menu item
menu.removeItem(R.id.action_to_be_performed);
}
}
Finally, call the Callback on your TextView with the editContextualActionBar method in onCreateActionMode and perform the menu action in onActionItemClicked:
textView.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
editContextualActionBar(mode, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_to_be_performed:
// perform action
return true;
default:
break;
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
});

openOptionsMenu function not working in ICS?

Im using action bar compability library. Im trying to open the options menu from a button with openOptionsMenu() function but it does nothing.
Menu shows as usual when pressing the menu key on my phone. What is wrong here?
public class ReadActivity extends ActionBarActivity {
...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean value;
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.read, menu);
value = super.onCreateOptionsMenu(menu);
if (Helper.SupportsNewApi()) {
getActionBar().hide();
} else {
((View) ((LinearLayout) findViewById(R.id.actionbar_compat))
.getParent()).setVisibility(View.GONE);
}
return value;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.menu_search:
// Toast.makeText(this, "Tapped search", Toast.LENGTH_SHORT).show();
break;
case R.id.menu_bookmark:
// selectText();
// setFullScreen(false);
break;
case R.id.menu_day_night_mode:
break;
case R.id.menu_settings:
break;
case R.id.menu_zoom_in:
showOverlay(false);
break;
case R.id.menu_zoom_out:
showOverlay(false);
break;
case R.id.menu_table_of_contents:
Intent tocIntent = new Intent(this, TocActivity.class);
int GET_SECTION_REFERENCE = 1;
startActivityForResult(tocIntent, GET_SECTION_REFERENCE);
break;
case R.id.menu_overflow:
Toast.makeText(this, "Tapped overflow", Toast.LENGTH_SHORT).show();
//closeOptionsMenu();
openOptionsMenu(); //tried the below aswell, no results
//getWindow().openPanel(Window.FEATURE_OPTIONS_PANEL, null);
break;
}
return super.onOptionsItemSelected(item);
}
#Override //disable volume buttons
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (!menuShown && (keyCode == 25 || keyCode == 24)) {
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
Log.d(tag, "Keycode is = "+keyCode);
if (keyCode == 82) {
if (!menuShown) {
//openOptionsMenu();
showOverlay(true);
} else {
showOverlay(false);
}
//don't want it to open when pressing menu
return true;
} else if (keyCode == 4 && menuShown) {
showOverlay(false);
return true;
} else if (keyCode == 25 && !menuShown) {
prevPage();
return true;
} else if (keyCode == 24 && !menuShown) {
nextPage();
return true;
}
return super.onKeyUp(keyCode, event);
}
}
I was having the same problem trying to go around this openOptionsMenu thing on an app
that I was doing that should run on Android 1.6 and up. Following the answer from Werner Van Belle I reached the conclusion that we could achieve a workaround to solve the problem.
So I came up with the following code, it's always beatiful when people don't mark a method as final, so we can always override it. It's perfect if you don't want to give up on targeting your app to the latest api (android:targetSdkVersion="17"). I hope you guys like it. :)
#Override
public void openOptionsMenu() {
Configuration config = getResources().getConfiguration();
if((config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK)
> Configuration.SCREENLAYOUT_SIZE_LARGE) {
int originalScreenLayout = config.screenLayout;
config.screenLayout = Configuration.SCREENLAYOUT_SIZE_LARGE;
super.openOptionsMenu();
config.screenLayout = originalScreenLayout;
} else {
super.openOptionsMenu();
}
}
To shed some light on this sad development by google. Google obviously wishes everybody to embrace the new ActionBar. They could have achieved that by making the ActionBar easier to use than the old menu system. That is however not how they planned the transition. No, they thought it would make sense to harras programmers by making the old menus impossible to use but without providing proper backward compatibility.
Below is the code taken from com.android.internal.policy.impl, which is supposed to create the optionsMenu panel. As you see, the code simply refuses to create an options Panel. Allthough, the ability is obviously there. So, to answer your question: forget it, Google doesn't want you to use that optionsPanel anymore.
// Don't open an options panel for honeycomb apps on xlarge devices.
// (The app should be using an action bar for menu items.)
if (st.featureId == FEATURE_OPTIONS_PANEL) {
Context context = getContext();
Configuration config = context.getResources().getConfiguration();
boolean isXLarge = (config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_XLARGE;
boolean isHoneycombApp = context.getApplicationInfo().targetSdkVersion >=
android.os.Build.VERSION_CODES.HONEYCOMB;
if (isXLarge && isHoneycombApp) {
return;
}
}
I cannot understand the forcing blocking Menu button usage as well. However, the following trick helped me with showing a menu on "restricted" types of devices.
First of all we need to define, whether we require the following hack or not.
boolean requireDirtyMenuButtonHack = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && (activity.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_XLARGE) > 0;
Then:
protected final OnClickListener mMenuButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (requireDirtyMenuButtonHack) {
Configuration config = getContext().getResources().getConfiguration();
config.screenLayout &= ~Configuration.SCREENLAYOUT_SIZE_XLARGE;
config.screenLayout |= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
getActivity().openOptionsMenu();
}
};
Don't forget to cleanup! (don't know if it's neccessary, but better to play kind)
public void onPrepareOptionsMenu(Menu menu) {
if (requireDirtyMenuButtonHack) {
Configuration config = getContext().getResources().getConfiguration();
config.screenLayout &= ~Configuration.SCREENLAYOUT_SIZE_LARGE;
config.screenLayout |= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
//do the preparing...
}
I'm not sure how relevant this is, but this forum post I found seems to be answerring the same question you have.
I hope this post is relevant enough to solve your problem.
Good luck!
android:targetSdkVersion="10" in manifest helped me.
openOptionsMenu() works as expected now on ICS+. In addition, there is "overflow" menu button appears at the bottom of screen (on device buttons panel).
ps: I use NoTitleBar theme (NoActionBar for sdk 11 and higher) +ViewPagerIndicator by Jake Wharton.
This worked for me, my code is pretty similar to yours, and what I want to do is from a button in the action bar, open the overflow menu:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_home_about:
dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.customdialog);
dialog.show();
break;
default:
case R.id.menu_home_refresh:
updateLists(true);
break;
case R.id.menu_home_menu:
new Handler().postDelayed(new Runnable() {
public void run() {
openOptionsMenu();
}
}, 0);
return true;
}
return false;
}
Do you mean you want to show a button on the right side of the action bar?
Here is how I did mine:
res/menu/main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menu_share"
android:title="Logout"
android:icon="#android:drawable/ic_lock_power_off"
android:orderInCategory="1"
android:showAsAction="always" />
</menu>
Activity
1) take note of the ActionBarActivity; 2) MenuInflater in onCreateOptionsMenu 3) onOptionsItemsSelected (I think you need to return super.onOptionsItemSelected(item) )
public class BaseActivity extends ActionBarActivity {
....
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
....
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_share:
//Do something
break;
}
return super.onOptionsItemSelected(item);
}
If you are using your custom toolbar, you can try:
toolBar.showOverflowMenu();

How can I populate a menu using intents?

How can I populate a menu using intents? I didn't understand that thing.
Or is there any better way for that?
Update:
Suppose I have an application that need to resize the image,and there are many other applications that have a capability of resizing the image. How can I show the list of applications on a menu in my application so that when clicking on a particular option it will invoke the intent associated with that application. Simply saying I could resize the image in my application with out bothering about how that will get done.
Here you have an example, using the onOptionsItemSelected that appears with the menu button you control what the menu does:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case HISTORY_ID: {
AlertDialog historyAlert = historyManager.buildAlert();
historyAlert.show();
break;
}
case SETTINGS_ID: {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.setClassName(this, PreferencesActivity.class.getName());
startActivity(intent);
break;
}
}
But we create the menu with this code:
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, SETTINGS_ID, 0, R.string.menu_settings)
.setIcon(android.R.drawable.ic_menu_preferences);
menu.add(0, HELP_ID, 0, R.string.menu_help)
.setIcon(android.R.drawable.ic_menu_help);
menu.add(0, ABOUT_ID, 0, R.string.menu_about)
.setIcon(android.R.drawable.ic_menu_info_details);
return true;
}

Categories

Resources