Как добавить кнопку в ActionBar(Android)?

Я хочу добавить кнопку на панель действий в правой части примера, как на этом снимке экрана:

скриншот панели действий без кнопок. заголовок 'Пример'

Я получаю actionBar в методе onCreate как:

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

и кнопка возврата (метод onOptionsItemSelected), как показано ниже:

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

Как я могу добавить кнопку?

3 ответа

Решение

Вы должны создать запись внутри res/menu,переопределение onCreateOptionsMenu и надуть это

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

запись для меню может быть:

<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>

An activity populates the ActionBar in its onCreateOptionsMenu() метод.

Вместо того, чтобы использовать setcustomview(), just override onCreateOptionsMenu как это:

@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() метод называется. 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;
}

Спасибо @Blackbelt! Новая подпись метода для раздувания меню:

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.my_meny, menu);
}
Другие вопросы по тегам