How to distinguish two clicks of a menu item in ActionBarSherlock?

I recently worked with ActionBarSherlock, and following various tutorials, I wrote this code to add items to the 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 do not know how to distinguish two clicks.

Although I found out that you need to override onOptionsItemSelected to handle clicks, and that the switch statement can be used to distinguish clicks, most manuals use element identifiers from their XML menus. Since I am not creating a menu in xml, how can I distinguish clicks without identifiers.

+6
source share
3 answers
 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); } } 
+17
source

Just check the 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); } } 
+1
source

you can do ti there Id in onOptionsItemSelected ................ which can also be set here

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. 
0
source

Source: https://habr.com/ru/post/917177/


All Articles