I have added a menu item in an android application.
Here is the code:
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add(1, 1, 0, "Item 1");
return true;
}
I need to show an alert dialog when user clicks the menu item.
My code for alert dialog
final Activity activity = this;
AlertDialog alertDialog = new AlertDialog.Builder(activity).create();
alertDialog.setTitle("Item 1");
alertDialog.setMessage("This is Item 1");
alertDialog.show();
Override onOptionsItemSelected. Your item id is 1. use switch case and show the diloag.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
AlertDialog alertDialog = new AlertDialog.Builder(ActivityName.this).create(); // You can use activity context directly.
alertDialog.setTitle("Item 1");
alertDialog.setMessage("This is Item 1");
alertDialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public abstract MenuItem add (int groupId, int itemId, int order, CharSequence title)
Added in API level 1
Add a new item to the menu. This item displays the given title for its label.
Parameters
groupId The group identifier that this item should be part of. This can be used to define groups of items for batch state changes. Normally use NONE if an item should not be in a group.
itemId Unique item ID. Use NONE if you do not need a unique ID.
order The order for the item. Use NONE if you do not care about the order. See getOrder().
title The text to display for the item.
Returns
The newly added menu item.
public boolean onOptionsItemSelected (MenuItem item)
Added in API level 1
This hook is called whenever an item in your options menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.
Derived classes should call through to the base class for it to perform the default menu handling.
Parameters
item The menu item that was selected.
Returns
boolean Return false to allow normal menu processing to proceed, true to consume it here.
Related
So I have a couple of settings fragments, and I want to do diffrent things when the 'save' icon is pressed, I can do this with toolbar.setOnMenuItemClickListener, but that would imply setting another listener for every other fragment, and that doesn't feel right, what's the right way to do this?
If I understand the question correctly, try the following:
In your fragments, override the method onOptionsItemSelected(). If you've correctly assigned the options menu save button an item id, you may write the following code to achieve what you want.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.save_button: // Be sure to replace this id with yours!
// <This is where you should put the code for the button's action>
return true;
}
return super.onOptionsItemSelected(item);
}
My problem is that I want to change the icon from a MenuItem from Visible to not being Visible, but this ofcourse needs to go via the onOptionsItemSelected. If I call on menu, it gets the MenuItem where is clicked on, while another one needs to be hidden. And I also checked on defining the MenuItem and findViewById, which didn't work because it's no view.
Let me show you a part of my code to make it more clear:
#Override
public boolean onOptionsItemSelected(MenuItem menu) {
switch (menu.getItemId()) {
case R.id.menu_refresh:
// Stuff
case R.id.menu_settings:
(Somehow point to R.id.menu_refresh).setVisible(false);
}
return super.onOptionsItemSelected(menu);
}
Any ideas?
What I read from the docs, there is a special method for this case: onPrepareOptionsMenu(Menu menu).
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.
So that makes it more like this:
#Override
public boolean onOptionsItemSelected(MenuItem menu) {
switch (menu.getItemId()) {
case R.id.menu_refresh:
// Stuff
case R.id.menu_settings:
showRefresh = false;
//Stuff
}
return super.onOptionsItemSelected(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.menu_refresh).setVisible(showRefresh);
return super.onPrepareOptionsMenu(menu);
}
If you're doing a 2.3 style menu, you don't change it in onOptionsItemSelected. You do it in onPrepareOptionsMenu the next time the menu is launched (by saving whatever data is appropriate to save).
If you have an actionbar, you'll need to call invalidateOptionsMenu on the activity to reload the menu, and do the disabling in the create function.
I'm 100% sure this is going to be one of those newbie questions, but here it goes...
Is there a way I can write a method in one activity and be able to access it from the others?
Example:
I have six activites in my app, each with it's own menu.xml because the options available for each need to be different, and I have these menus & menuitems set up as shown:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.calculator_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//Handle item selection
switch (item.getItemId()) {
case R.id.menuItem_calculator_Help:
helpDialogGo();
return true;
case R.id.menuItem_calculator_Settings:
//settingsActivityGo();
return true;
case R.id.menuItem_calculator_Share:
shareGo();
return true;
case android.R.id.home:
// app icon in Action Bar clicked; go home
Intent uptohome = new Intent(this, Main.class);
uptohome.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(uptohome);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
The an example of one of these methods is:
private void helpDialogGo() {
Toast.makeText(this, "help", Toast.LENGTH_LONG).show();
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Sorry, no help has been written since this application is still in development. This is a prerelease version.")
.setCancelable(false)
.setPositiveButton("Cool", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'Yes' Button
dialog.cancel();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Pixel Help");
// Icon for AlertDialog
alert.setIcon(R.drawable.question);
alert.show();
}
So is there a way to have this custom method shared among all the activities and run it when the button is pressed in each of them, as to avoid having large amounts of code replicated across my app?
And if so, are there any potholes that I may hit? (Some of the menu items are going to bring up dialogs, others will take the user to a new activity)
Do you have similar menuitems in every activity? i.e. same number of items but different behaviour? If yes...
How about creating a BaseActivity which overrides onCreateOptionsMenu and onOptionsItemSelected() methods.. (As you have given in the above example). All your activities should inherit from this BaseActivity and then override the menu handling methods. eg. helpDialogGo() will go to the new class.
so the BaseActivity will have onCreateOptionsMenu and onOptionsItemSelected() methods. Plus all the menuItem actions (i.e. helpDialogGo() etc) as empty methods. The inherited classes will overide menuItem Actions.
If the menuitems are not similar in each activity, you are better off creating menu for each activity.
EDIT:
Not sure what you expect more. I thought I made it clear. Let me try again.
Class BaseActivity extends Activity.
BaseActivity extends Activity {
// Copy your onCreateOptionsMenu() and onOptionsItemSelected() methods here
protected void helpDialogGo() { }
// ... other methods
}
Class MyActivity1 extends BaseActivity.
MyActivity1 extends BaseActivity {
// Copy your helpDialogGo() code in full here and then make
// any specific changes to menu behaviour based on activity.
}
Class MyActivity2 extends BaseActivity
MyActivity2 extends BaseActivity {
// Copy your helpDialogGo() code in full here and then make
// any specific changes to menu behaviour based on activity.
}
One way, of course, is to created some custom classes that encapsulate your desired functionality - and use those within your activities. It's a better abstraction than placing the implementation directly in the Activity(s) itself (all things being equal, and based on what you described so far).
Any time you find yourself duplicating an implmentation that's a flag reminding you this is a good place to roll that code into its own class - usually.
In my project i have activity with options menu. I override onOptionsItemSelected method and add my handlers to menu items (switch-case block). But in one handler i need access to another menu item, how i can do that? findViewById doesn't work
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.visit:
//how to access another MenuItem from here?
return true;
}
...
When creating your menu items, you could put the MenuItem you want to check in an attribute (i.e. one of the private fields of your class). This way, when you go into your method, you'll be able toacces the other menu item.
I'm used to working in J2ME. I wanted to do something on Android, but I just can't get how to replace the command class in the events Android scenario.
Do you want to add commands and want them appear in a built-in menu? When user selects one of them you want a predefined function to be called? If I understand your question right and your problem is the same as above here is the solution:
Android provides a built-in menu and let you create your own menu options. Just like in J2ME as you create some menu options(commands in J2ME) they appear in menu automatically.(The menu that appears when the user hits the menu key on the handset)
To add menu to your Activity override onCreateOptionsMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_ITEM_ID, 0, "First Menu Option");
return true;
}
Then when user selects an item in the menu onMenuItemSelected(int featureId, MenuItem item) callback is invoked. So you can catch your menu option as follows:
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case MENU_ITEM_ID:
yourFunction(); //your function for this particular item
return true;
}
return super.onMenuItemSelected(featureId, item);
}
If there were more items(options) in menu, you would catch them in switch by their ids.
hope that helps