How to add button in ActionBar(Android)?

2020-01-27 02:23发布

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?

3条回答
三岁会撩人
2楼-- · 2020-01-27 03:04

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>
查看更多
贼婆χ
3楼-- · 2020-01-27 03:06

Thanks to @Blackbelt! The new method signature for inflating the menu is this:

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.my_meny, menu);
}
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-01-27 03:15

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;
}
查看更多
登录 后发表回答