4

I am using new toolbar component from AppCompat library. I am trying to show action buttons on my toolbar but they never show up.

<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_login"
        android:title="@string/action_login"
        android:orderInCategory="100"
        app:showAsAction="ifRoom" />
</menu>

My activity

@Override
protected void onCreate(Bundle savedInstanceState) {

    //...

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
            toolbar, R.string.drawer_open, R.string.drawer_close);
    toolbar.setTitle(R.string.title_activity_posts);
    drawerLayout.setDrawerListener(actionBarDrawerToggle);
    if (getSupportActionBar() != null)
    {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }
    actionBarDrawerToggle.syncState();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return super.onCreateOptionsMenu(menu);
}

What am I missing?

Andrei
  • 42,814
  • 35
  • 154
  • 218

2 Answers2

5

I don't know which type of Activity used. However, using AppCompat/support Toolbar also need to initialize.

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null)
{
        setSupportActionBar(toolbar);//To display toolbar

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setElevation(0); // or other...
}

See more at this

T D Nguyen
  • 7,054
  • 4
  • 51
  • 71
0

you forgot to give it an icon, and sometimes you must change app:showAsAction to always like this:

  <item
    android:id="@+id/action_login"
    android:title="@string/action_login"
    android:orderInCategory="100"
    android:icon="@drawable/ic_action_login"
    app:showAsAction="always" />
Sadik anass
  • 282
  • 4
  • 9