如何更改Android操作栏中的向上按钮图标?

时间:2016-04-09 09:57:57

标签: android android-navigation-drawer

我想更改Android操作栏中的向上按钮图标以显示导航抽屉菜单图标。我正在尝试这个似乎有效,但这是正确的方法吗?

    private void configureToolbar() {

    if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
        mToolbar = (Toolbar) findViewById(R.id.drawer_toolbar);
        mToolbar.setTitle(getResources().getString(R.string.navigation_drawer_title));
        setSupportActionBar(mToolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    } else {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle(getResources().getString(R.string.officer_activity_title));
        setSupportActionBar(mToolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.menu);
    }

    setDrawerToggle();

}

考虑到android.support.v4.app.ActionBarDrawerToggle已被弃用,而新的support.v7 class不允许您将drawable图标传递给其构造函数。

1 个答案:

答案 0 :(得分:0)

impost android.support.v7.app.ActionBarDrawerToggle并使用工具栏

toolbar = (Toolbar) findViewById(R.id.toolbar);

        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }

    mDrawerToggle = new ActionBarDrawerToggle(
                this,
                mDrawerLayout,
                toolbar,
                R.string.drawer_open, R.string.drawer_close){
                        @Override
                        public void onDrawerOpened(View drawerView) {
                            super.onDrawerOpened(drawerView);
                            // code here will execute once the drawer is opened 
                            getSupportActionBar().setTitle(mTitle);
                            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
                        }
                        @Override
                        public void onDrawerClosed(View drawerView) {
                            super.onDrawerClosed(drawerView);
                            // Code here will execute once drawer is closed
                            getSupportActionBar().setTitle(mDrawerTitle);
                            invalidateOptionsMenu();
        };

在工具栏

的xml中添加以下代码
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    />