35

I want to add a Button to the Action Bar to the right hand side of Example as in this screen shot:

a screenshot of an actionbar with no buttons. the title is 'Example'

I get actionBar in onCreate method as:

ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); 

and back button(onOptionsItemSelected method) as below:

public boolean onOptionsItemSelected(MenuItem item){ Intent myIntent = new Intent(getApplicationContext(),MainActivity.class); startActivityForResult(myIntent, 0); return true; } 

How can I add button?

2 Answers 2

89

you have to create an entry inside res/menu,override onCreateOptionsMenu and inflate it

@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.yourentry, menu); return true; } 

an entry for the menu could be:

<menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/action_cart" android:icon="@drawable/cart" android:orderInCategory="100" android:showAsAction="always"/> </menu> 
Sign up to request clarification or add additional context in comments.

6 Comments

Ok.That works.But i dont understand use of orderInCategory and its value as 100.
It is an integer that represent the order of "importance" of the item, within a group. You can change it. As long as you have one or two elementes in the menu it does not make difference. you can read about it here
Thank you.Now another question is that I add this menu in another activity but show different button instead of this.So how can i do that?
Oh,I understood that i have to create different file under res/menu to use different menu in another activity.By the way thank you.
Can we change the location of the button?? I'm getting it on extreme right. Can I have it in center??
|
22

An activity populates the ActionBar in its onCreateOptionsMenu() method.

Instead of using setcustomview(), just override onCreateOptionsMenu like this:

@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mainmenu, menu); return true; } 

If an actions in the ActionBar is selected, the onOptionsItemSelected() method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:

@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menuitem1: Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show(); break; case R.id.menuitem2: Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show(); break; } return true; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.