Android工具栏操作按钮未显示

4

我正在使用来自AppCompat库的新工具栏组件。我试图在我的工具栏上显示操作按钮,但它们从未显示出来。

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

我的活动

@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);
}

我错过了什么吗?

2个回答

5

我不知道使用哪种类型的Activity。然而,如果使用AppCompat/support Toolbar,也需要进行初始化。

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

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

点击此处查看更多相关IT技术内容。


确实。我漏掉了 setSupportActionBar(toolbar); - Andrei

0

你忘了给它一个图标,有时候你必须将app:showAsAction更改为always,像这样:

  <item
    android:id="@+id/action_login"
    android:title="@string/action_login"
    android:orderInCategory="100"
    android:icon="@drawable/ic_action_login"
    app:showAsAction="always" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接