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.
Related
I want to make a navigation drawer which will populate by listview. Now i want that by clicking each item of the list, open a fragment as per my choice. How do I do this?
The NavigationDrawer doesn't use a ListView in the menu, NavigationDrawer uses directly Menu Items it means that in your source code you can add programmatically items to your menu as you need.
Your NavigationDrawer activity or whatever you named
you can add items to the menu using the
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// To Inflate the menu:
// this adds items to the navigation drawer menu if it is present.
getMenuInflater().inflate(R.menu.dashboard, menu);
return true;
}
by default this method create a static menu using a XML layout in the res/menu/menu_file.xml
but if you follow the next source code you will be able to add more items to your navigation drawer programmatically
the Method add() overloads:
add (int titleRes)
add (CharSequence title)
add (int groupId, int itemId, int order, int titleRes);
add (int groupId, int itemId, int order, CharSequence title);
if you already have all the names of your new menu items in an array like itemsName
you can use something like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
for(String itemName : itemsName){
int itemId = Arrays.asList(itemsName).indexOf(itemName);
menu.add(Menu.NONE, itemId, Menu.NONE, itemName);
}
return true;
}
and to manage the click event, on every one, you need to solve it depending on your array of actions to take, in your dynamic array, because you need to know deterministic every action that your menu item need to do or behave, as a menu option.
But in general your click listener for those menu items you use something like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
//here you need the logic of what action
//your item is going to take
//but that is up to you
//how do you want to know what to do
//with a dynamic unknown array of options.
if (itemId == 0){
doSomething();
return true;
}
return false;
}
}
enjoy!!!
I have an Actionbar displayed on my maps fragment to which I have added a zoom-in button. When selected I would like to replace it with a zoom-out button.
When zoom-in is selected the it is obviously pases in to onOptionsItemSelected as the menu item, so it is easy to set it's attributes like this: viewZoomIn.setVisibility(viewZoomIn.GONE); My problem is, how do I get a reference to the zoom-out button on the action bar to set it as as I would like to viewZoomOut.setVisibility(viewZoomOut.VISIBLE);?
I thought I may be able to store the zoom-in and zoom-out views as instance variables and capture them when I inflate the Actionbar, like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
viewZoomIn = findViewById(R.id.zoom_in);
viewZoomOut = findViewById(R.id.zoom_out);
return super.onCreateOptionsMenu(menu);
This does not work.
Any help on getting hold of thes buttons, or advice on a better way of toggling my zoom-in/zoom-out buttons would be appreciated.
It probably shows, but I am pretty new to Java, so it would be preferable is any assistance were communicated in a simple manner.
Thank you.
You have to apply your visibility logic in onPrepareOptionsMenu(Menu) not in onCreateOptionsMenu(Menu) if you want to toggle MenuItem state.
private boolean currentlyZoomedIn;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// called the first time and after each "invalidateOptionsMenu()"
// if tha Activity is in the "zoomedIn" state, the zoomOut button will be visible
menu.findItem(R.id.zoom_in).setVisible(!currentlyZoomedIn);
menu.findItem(R.id.zoom_out).setVisible(currentlyZoomedIn);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.zoom_in:
// do your logic when zoom_in is clicked
currentlyZoomedIn = true;
break;
case R.id.zoom_out:
// do your logic when zoom_out is clicked
currentlyZoomedIn = false;
break;
}
// force the redraw of the menu
invalidateOptionsMenu();
return super.onOptionsItemSelected(item);
}
By the way, I suggest you to use only one button and move your logic only in onOptionsItemSelected(MenuItem) to avoid an instance variable and the call to invalidateOptionsMenu() in a way like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// zoom_out_in_id is the id for the common button
if (item.getItemId() == R.id.zoom_out_in_id) {
// get the curren title
final CharSequence title = item.getTitle();
// if the current title is the one of zoom_in button, you have to change its infos to zoom_out ones
if (title.equals("zoom_in_title")) {
// do your logic when zoom_in is clicked
item.setIcon(R.drawable.zoom_out_icon);
item.setTitle("zoom_out_title");
} else if (title.equals("zoom_out_title")) {
// do your logic when zoom_out is clicked
item.setIcon(R.drawable.zoom_in_icon);
item.setTitle("zoom_in_title");
}
}
return super.onOptionsItemSelected(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
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);
}
How can I implement a custom onClickListener for the Home button of the Action Bar?
I already did a getSupportActionBar().setDisplayHomeAsUpEnabled(true); and now I want to redirect the user to a certain activity in case the Home button is clicked.
I tried with:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
item.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Intent i = new Intent();
i.setClass(BestemmingActivity.this, StartActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
return true;
}
});
default:
return super.onOptionsItemSelected(item);
}
}
but it never enters in the onMenuItemClick.
Basically, it's done just like in this link but still it doesn't enter in the listener.
if anyone else need the solution
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed(); return true;
}
return super.onOptionsItemSelected(item);
}
I use the actionBarSherlock,
after we set supportActionBar.setHomeButtonEnabled(true);
we can override the onMenuItemSelected method:
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case android.R.id.home:
toggle();
// Toast.makeText(this, "home pressed", Toast.LENGTH_LONG).show();
break;
}
return true;
}
if we use the system given action bar following code works fine
getActionBar().setHomeButtonEnabled(true);
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case android.R.id.home:
//do your action here.
break;
}
return true;
}
Fixed: no need to use a setOnMenuItemClickListener.
Just pressing the button, it creates and launches the activity through the intent.
Thanks a lot everybody for your help!
answers in half part of what is happening. if onOptionsItemSelected not control homeAsUp button when parent activity sets in manifest.xml system goes to parent activity. use like this in activity tag:
<activity ... >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.activities.MainActivity" />
</activity>
You need to explicitly enable the home action if running on ICS. From the docs:
Note: If you're using the icon to navigate to the home activity, beware that
beginning with Android 4.0 (API level 14), you must
explicitly enable the icon as an action item by calling
setHomeButtonEnabled(true) (in previous versions, the icon was enabled
as an action item by default).
Best way to customize Action bar onClickListener is onSupportNavigateUp()
This code will be helpful link for helping code
you should to delete your the Override onOptionsItemSelected and replate your onCreateOptionsMenu with this code
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_action_bar_finish_order_stop, menu);
menu.getItem(0).setOnMenuItemClickListener(new FinishOrderStopListener(this, getApplication(), selectedChild));
return true;
}