How to find the position clicked from onOptionsItemSelected - android

I have a Gallery view, In this view I set up an options menu
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, EMAIL_MENU_ID, 0, "Email");
menu.add(0, SHARE_MENU_ID, 0, "Share");
menu.add(0, RATE_MENU_ID, 0, "Rate");
menu.add(0, BUY_MENU_ID, 0, "Buy");
return true;
}
I have the following method to get the option item selected.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case EMAIL_MENU_ID:
sendMail(index);
case SHARE_MENU_ID:
postToWeb(index);
case RATE_MENU_ID:
postRating(index);
case BUY_MENU_ID:
buy(index);
}
return super.onOptionsItemSelected(item);
}
How could i find the item of the Gallery view that's currently in focus?

Very good tutorial. In my scenario the user has pressed the Menu button and I would like to present the user with some options to take on the image that is currently in focus. At this point the user has not clicked on the image so I don't have the position that you would normally get when a user selects an item. I've thought about using a context menu instead but was hoping to use an options menu.

Related

Dynamic option menu --> how to get the selected item?

I'm trying to create a android menu which should be build dynamically inside a Google Glass app. Therefore I have to arrays which contain the diffent kinds of objects which should be displayed in the menu.
The menu should look like the following:
Menu1
Option1
Option2
Option3
Menu2
Option1
Option2
Menu3
Menu4
I've already build up the menu structure with this code:
public boolean onCreateOptionsMenu(Menu menu) {
menu.clear();
SubMenu damageCodes = menu.addSubMenu(R.string.chooseDamageCode).setIcon(R.drawable.ic_document_50);
int i = 0;
for(Damagecode d : this.mDamagecodes){
damageCodes.add(0, Menu.NONE, i, d.getCotext());
i++;
}
SubMenu priorities = menu.addSubMenu(R.string.choosePriority).setIcon(R.drawable.ic_document_50);
i = 0;
for(Priority p : this.mPriorities){
priorities.add(1, Menu.NONE, i, p.getPriokx());
i++;
}
menu.add(3, Menu.NONE, Menu.NONE, R.string.setConfirmationText).setIcon(R.drawable.ic_pen_50);
menu.add(4, Menu.NONE, Menu.NONE, R.string.backToTplnr_equipment).setIcon(R.drawable.ic_reply_50);
getMenuInflater().inflate(R.menu.create_notification, menu);
return true;
}
I know that the method
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
}
is called when a menuitem is selected but the question right now is how to get the selected item?
Just put a switch inside the onMenuItemSelected:
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getTitle()) {
case R.string.chooseDamageCode:
// do stuff here for damagecode item
break;
case R.string.choosePriority:
// do stuff here for choosepriority item
break;
...same for other items
}
}
Hope this helps
I found a solution.
Due to the fact that I don't know which elements / values can be in my array I created a simple flag. This means... I'm creating the main menu where every item has a fixed unique ID. The submenu elements do not have a unique id, they only have the title. So what I'm doing right now is to check first whether one of the main menu items was pressed (unique ID) or whether the title of the clicked element is either in one of the arrays or not.
Works quite fine :)
Hope this helps anybody else too!
Greetings

How can I give option Menu in Application?

I want to give Option menu in my application and also that menu are clickable. If I click any menu than it will open another activity. So, please help me for this. In my application there is many class or activity i want to put this optionmenu in every activity of my application. here i try with this kind of code.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuItem dashboard = menu.add(0, 1, 1, "Dashboard");
MenuItem roles = menu.add(0, 2, 2, "Roles");
MenuItem profiles = menu.add(0, 3, 3, "Profiles");
MenuItem move = menu.add(0, 4, 4, "Move Product");
MenuItem assignedproduct = menu.add(0, 5, 5, "Assigned Product Report");
MenuItem salesreport = menu.add(0, 6, 6, "Sales Report");
MenuItem salesreturn = menu.add(0, 7, 7, "Sales Return");
MenuItem purchasereport = menu.add(0, 8,8, "Purchase Report");
MenuItem logout = menu.add(0, 9, 9, "Logout");
super.onCreateOptionsMenu(menu);
return true;
You need to override onCreateOptionsMenu function in each activity of your app. that's the only way
To give the click functionality to menu items, you will have to override the onOptionsItemSelected() method. Then give those MenuItems their respective action based on their item id as follows...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
// give action to the menu item which id is 1
return true;
case 2:
// give action to the menu item which id is 2
return true;
case 3:
// give action to the menu item which id is 3
return true;
case 4:
// give action to the menu item which id is 4
return true;
..........
..........
default:
return super.onOptionsItemSelected(item);
}
}
If all of your activities should have same menu, best way is move creating menu in superclass. . Name it MenuActivity, for example. In this class override onCreateOptionsMenu for creating menu and onOptionsItemSelected for handling user taps. Then just inherit all your activities from MenuActivity.

Android and menus

I'm a Java programmer with experience. I started working on a small Android project and i got soooo frustrated by how much Android has complicated programming just to be more flexible.
Exactly, the problem i have is as follows: i have a menu item that i need to use in several menus inside mu app. Is there a way to create a menu item object (possible associate some function to it) and just pass it around so any activity can add it to it's own contex menu?
I have tried this:
Created a "res.menu.mymenu.xml" file that contains a menu item with the same id as menu item from another "res.menu.mymenu2.xml" file. Then i have tried this:
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(getMenuToInflate(), menu);
menu.add(0, R.id.mnhidefrom, 0, ((MenuItem)findViewById(R.id.mnhidefrom)).getTitle());
HideMenuAction.prepareAndGetHideMeMenuItem(menu, menuInfo); //creating an intent for "hide" menu item that will hold some data needed when user clicks the menu item.
}
But no luck... I got "null pointer exception" on "menu.add" line...
Is there a normal, object oriented way, to create a menu item that will know what it should do regardless of anything outside (like,say, menu it belongs to) and just pass it around like any other object and add it to any menu i like (just like i can do with Swing menu and JMenuItems)?
Ahmad has half the story. This will give you a base of menu options that are always available. The way to add menu options specific to each extending activity is to write a Fragment for it. The fragment will included in the activity layout, but you can make it take up no room or use it for padding. When a Fragment implements onCreateOptionsMenu, the choices it adds are merged with the ones that the Activity created.
Read everything to do with the options menu in this guide for more details:
http://developer.android.com/guide/topics/ui/menus.html
Is there a normal, object oriented way
Yes there is. It's called inheritance!
Create a base Activityin which you inflate the OptionsMenu once and extend this Activity for all your Activities.
public class BaseActivity extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.blabla:
// do something
break;
case R.id.blablab:
// do something
break;
}
return true;
}
}
Now you can do this:
public class MainActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
return true;
}
}
I used a BaseActivity as Ahmad described. It works fine.
Now I want to show a special menu item in one specific Activity (which extends the BaseActivity).
#Override
public boolean onOptionsItemSelected(android.view.MenuItem item) {
switch (item.getItemId()) {
case 0:
Intent intent = new Intent(this, BlaActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(Menu.NONE, 0, 0, "Edit");
item.setIcon(R.drawable.content_edit);
return super.onCreateOptionsMenu(menu);
}
This works as I expected, but I can't get the new inserted menuitem to get in the first position.
I need it to be in first position, so it is displayed directly in the ActionBar and the user sees that there is a new option without clicking on the options button.
Edit: I just found the solution myself.
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(Menu.NONE, 0, 0, "Bearbeiten");
item.setIcon(R.drawable.content_edit);
if (android.os.Build.VERSION.SDK_INT >= 11) {
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); //<-----
}
return super.onCreateOptionsMenu(menu);
}

Android - Finish() restarts current activity

I have an activity that refuses to close the first time finish() is called. I had originally put a Cancel button in the activity, but then I noticed that it exhibits the same behavior when I use the Back button too. It can be described like this:
1. The activity opens, and the appropriate data is filled in (which came from a List View from the previous activity).
2. Press the Back button, and all the fields are cleared of data, but it doesn't return the user to the original activity.
3. Press the Back button again, and the user is returned to the original activity.
I can post code, but I'm not sure if the issue is in the current activity or the main one. I can mention that switched to using a context menu to open the Activity.
UPDATE:
Ok, looks like both of these suggestions were correct, the main activity is indeed launching 2 versions of the Edit activity. Now I'm just trying to figure out why. I noticed this happening when I switched over to a context menu for the list item options. The Add button is a Menu Item, however. Here is the relevant code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// add(int groupId, int itemId, int order, int titleRes)
menu.add(0, INSERT_ID, 0, R.string.menu_insert);
menu.add(0, SETTINGS_ID, 1, R.string.sharedPrefButton);
menu.add(0, COMMON_DESC_ID, 2, R.string.commonDescButton);
menu.add(0, RESET_ID, 3, R.string.menu_reset);
return true;
}
/*
* This is going to handle the "Add Expenditure" menu item. When this is selected, the
* onOptionsItemSelected() method will be called with the item.getId() set to INSERT_ID
* (the constant we used to identify the menu item).
*/
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case INSERT_ID:
createExpenditure();
break;
case SETTINGS_ID:
manageSharedPrefs();
break;
case COMMON_DESC_ID:
manageCommonDesc();
break;
}
return super.onMenuItemSelected(featureId, item);
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
menu.add(0, EDIT_ID, 0, R.string.menu_edit);
}
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int itemId = item.getItemId();
switch(itemId) {
case DELETE_ID:
mDbHelper.deleteExpenditure(info.id);
fillData();
break;
case EDIT_ID:
Intent i = new Intent(this, ExpenditureEdit.class);
i.putExtra(ExpendituresDbAdapter.KEY_ROWID, info.id);
startActivityForResult(i, ACTIVITY_EDIT);
break;
}
return super.onContextItemSelected(item);
}
It appears that you starting the same Activity twice. This is your Activity stack:
Original Activity, starts ListActivity
ListActivity (no data in fields), starts another instance of itself
ListActivity (fill in appropriate data)
Now when you push the back button:
ListActivity, close this second instance but...
ListActivity (still no data), the first instance resumes, so push back again
Original Activity
(Without code I cannot help you move than to describe what I think is happening...)
This is happening because apparently onMenuItemSelected is called whenever onContextItemSelected is executed. Although I'm still unsure as to why, if I use a conditional inside my onMenuItemSelected method, everything seems to work fine:
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (featureId == Window.FEATURE_CONTEXT_MENU)
{
Log.i("EZBudget","Context Menu");
}
else if (featureId == Window.FEATURE_OPTIONS_PANEL)
{
switch(item.getItemId()) {
case INSERT_ID:
createExpenditure();
break;
case SETTINGS_ID:
manageSharedPrefs();
break;
case COMMON_DESC_ID:
manageCommonDesc();
break;
}
}
return super.onMenuItemSelected(featureId, item);
}
I found this answer in another post: onContextItemSelected doesn't get called

How to distinguish two menu item clicks in ActionBarSherlock?

I have been working with ActionBarSherlock recently, and follwing various tutorials, I wrote this code to add items to Action bar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("Refresh")
.setIcon(R.drawable.ic_action_refresh)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menu.add("Search")// Search
.setIcon(R.drawable.ic_action_search)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return true;
}
However, I dont know how to distinguish the two clicks.
Although I did find out that you have to Override onOptionsItemSelected to handle the clicks and also that a switch statement can be used to distinguish between clicks, but most tutorials use item ids from thier xml menus. Since I am not creating menus in xml how can i distinguish the clicks without ids.
private static final int REFRESH = 1;
private static final int SEARCH = 2;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, REFRESH, 0, "Refresh")
.setIcon(R.drawable.ic_action_refresh)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menu.add(0, SEARCH, 0, "Search")
.setIcon(R.drawable.ic_action_search)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case REFRESH:
// Do refresh
return true;
case SEARCH:
// Do search
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Just check following
http://developer.android.com/guide/topics/ui/actionbar.html
which contains
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { <--- here you can get it
case android.R.id.home:
// app icon in action bar clicked; go home
Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
you can do ti by there Id in onOptionsItemSelected ................which can be set here also
http://thedevelopersinfo.wordpress.com/2009/10/29/handling-options-menu-item-selections-in-android/
http://developer.android.com/reference/android/view/Menu.html#add(int, int, int, java.lang.CharSequence)
use
public abstract MenuItem add (int groupId, int itemId, int order, CharSequence title)
Since: 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.

Categories

Resources