Android支持工具栏+ ActionBarDrawerToggle不更改为箭头

时间:2014-11-11 10:56:38

标签: android navigation-drawer toolbar drawertoggle

我在工具栏和抽屉里挣扎。我在向Backstack添加新片段时尝试将汉堡切换为箭头但是没有办法实现。

也许我错过了一些东西,但我找不到办法。有人有同样的问题吗?

这是宣言:

mDrawerToggle = new ActionBarDrawerToggle(
            getActivityCompat(),                    /* host Activity */
            mDrawerLayout,                    /* DrawerLayout object */
            ((BaseActivity) getActivityCompat()).getToolbar(),
            R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
            R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
    )

这是我将片段添加到后栈时调用的函数

public void setToggleState(boolean isEnabled) {
    if (mDrawerLayout == null)
        return;

    if (isEnabled) {
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        mDrawerToggle.onDrawerStateChanged(DrawerLayout.LOCK_MODE_UNLOCKED);
    } else {
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        mDrawerToggle.onDrawerStateChanged(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    }
    mDrawerToggle.syncState();
}

5 个答案:

答案 0 :(得分:31)

我认为您所要做的就是删除第三个参数。因此:

mDrawerToggle = new ActionBarDrawerToggle(
     getActivityCompat(),              /* host Activity */
     mDrawerLayout,                    /* DrawerLayout object */
     // ((BaseActivity) getActivityCompat()).getToolbar(), <== delete this argument
     R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
     R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
    );

愿它有所帮助。

答案 1 :(得分:12)

我遇到了同样的问题。我的解决方案是:

确保您的活动实现onBackStackChangedListener。在你的活动中#39; onCreate我设置了backstack监听器并设置了工具栏

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mFm = getFragmentManager();
    mFm.addOnBackStackChangedListener(this);

    // Setup toolbar
    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    mToolbar.setVisibility(View.VISIBLE);
    setSupportActionBar(mToolbar);

    // Setup drawer toggle
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.menu_open, R.string.menu_close);
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    getSupportActionBar().setHomeButtonEnabled(true);
    mDrawerToggle.syncState();

    // Setup initial fragment
    if (savedInstanceState == null) {
        mCurrentFragment = DashboardFragment.newInstance();
        mFm.beginTransaction().add(CONTAINER_ID, mCurrentFragment).commit();
    }
}

还记得设置:

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    mDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    mDrawerToggle.onConfigurationChanged(newConfig);
}

现在魔术发生在onBackStackChanged()上。将最顶层片段的setDrawerIndicatorEnabled设置为true,将该片段设置为setDisplayHomeAsUpEnabled为false。反向其他的。我也不得不打电话给syncState,否则汉堡包就不会再出现了:

@Override
public void onBackStackChanged() {
    mDrawerToggle.setDrawerIndicatorEnabled(mFm.getBackStackEntryCount() == 0);
    getSupportActionBar().setDisplayHomeAsUpEnabled(mFm.getBackStackEntryCount() > 0);
    mDrawerToggle.syncState();
}

答案 2 :(得分:2)

我使用以下布局实现了它: 我使用过ActionBarDrawerToggle v7 Drawer.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.toolbar.Drawer" >

    <include
        android:id="@+id/tool1"
        layout="@layout/toolbar" />



    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawerLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/tool1" >

        <FrameLayout
            android:id="@+id/mainContent"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
        </FrameLayout>

        <!-- Nav drawer -->

        <ListView
            android:id="@+id/drawerList"
            android:layout_width="240dp"
            android:layout_height="match_parent"
            android:layout_gravity="left"
            android:background="@android:color/white"
            android:divider="@android:color/white"
            android:dividerHeight="8dp"
            android:drawSelectorOnTop="true"
            android:headerDividersEnabled="true" />
    </android.support.v4.widget.DrawerLayout>

</RelativeLayout>

toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app1="http://schemas.android.com/apk/res/com.example.toolbar"
    android:id="@+id/my_awesome_toolbar"
    android:layout_width="fill_parent"
    android:layout_height="75dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app1:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app1:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" >

</android.support.v7.widget.Toolbar>

Drawer.java

package com.example.toolbar;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class Drawer extends ActionBarActivity {

    ActionBarDrawerToggle mDrawerToggle;
    private String[] days;
    ArrayAdapter<String> adapter;
    private ListView mDrawerList;
    DrawerLayout mDrawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.drawer);

        days = new String[] { "sunday", "monday", "tuesday", "wednesday",
                "thursday", "friday", "saturday" };
        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, days);
        mDrawerList = (ListView) findViewById(R.id.drawerList);
        mDrawerList.setAdapter(adapter);
        mDrawerList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub

                Fragment fragment = new MyFragment();
                Bundle args = new Bundle();
                args.putString(MyFragment.ARG_PLANET_NUMBER, days[position]);
                // args.putInt(MyFragment.ARG_PLANET_NUMBER, position);
                fragment.setArguments(args);

                FragmentManager fragmentManager = getSupportFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.mainContent, fragment).commit();

            }

        });

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

        setSupportActionBar(toolbar);
        toolbar.setTitle("ToolBar Demo");
        toolbar.setLogo(R.drawable.ic_launcher);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar,
                R.string.open_navigation_drawer,
                R.string.close_navigation_drawer) {

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                // TODO Auto-generated method stub
                super.onDrawerSlide(drawerView, slideOffset);
            }

            /** Called when a drawer has settled in a completely closed state. */
            @Override
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getSupportActionBar().setTitle("hello");
            }

            /** Called when a drawer has settled in a completely open state. */
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getSupportActionBar().setTitle("hi");
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        // getSupportActionBar().setDisplayHomeAsUpEnabled(true); //<---- added
        // getSupportActionBar().setHomeButtonEnabled(true); //<---- added

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) { // <---- added
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) { // <---- added
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState(); // important statetment for drawer to
                                    // identify
                                    // its state
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) { // <---- added
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(Gravity.START | Gravity.LEFT)) { // <----
                                                                        // added
            mDrawerLayout.closeDrawers();
            return;
        }
        super.onBackPressed();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

答案 3 :(得分:2)

@ hata的答案在大多数情况下是现场的。

但实际上,使用工具栏作为ActionBarDrawerToggle(...)构造函数的参数,你没有错。

当然,如果您使用股票Toolbar AppCompatActivity提供,使用库存Theme.AppCompat.Light根主题,那么这样做没有任何意义。 即使您希望在布局中使用自定义Toolbar,例如如果您正在实施Material Design的超级工具栏状态栏导航抽屉模式,您仍然可以调用setSupportActionBar(toolbar)并仍然不会将工具栏传递给ActionBarDrawerToggle()让活动处理导航图标。

但是,如果您真的想将ActionBarDrawerToggle绑定到Toolbar那不是活动的操作栏,并且可能有不同的样式和不同的图标或其他 - 还有一段路要走。

问题是,当你没有将工具栏作为第四个参数传递时,活动应该提供导航图标(箭头) - AppCompatActivity返回{{1}的值属性 - 它在任一标准AppCompat主题中定义。

但是,当您明确传递homeAsUpIndicator时,Toolbar期望工具栏实例提供可绘制的导航指示器 - 而且它不会,因为即使您应用适当的样式它是这样的:

ActionBarDrawerToggle

由于某种原因(可能它甚至是一个错误),<android.support.v7.widget.Toolbar ... app:theme="?actionBarTheme" style="@style/Widget.AppCompat.Toolbar"> 样式没有Widget.AppCompat.Toolbar属性,因此navigationIcon会返回Toolbarnull要求输入导航图标时。因此,为了解决这个问题,您只需从样式派生并添加属性:

ActionBarDrawerToggle

现在您可以使用工具栏感知构造函数<android.support.v7.widget.Toolbar ... app:theme="?actionBarTheme" style="@style/MyWidget.Toolbar"> <!-- styles.xml --> <style name="MyWidget.Toolbar" parent="Widget.AppCompat.Toolbar"> <item name="navigationIcon">?homeAsUpIndicator</item> </style> ,并且仍然具有导航图标。

答案 4 :(得分:1)

此行确保点击时汉堡包图标更改为箭头。确保在代码中写明了这一点。

mDrawerLayout.setDrawerListener(mDrawerToggle);