22

我在工具栏和抽屉上苦苦挣扎。当我将新片段添加到后台堆栈时,我试图将汉堡切换到箭头,但没有办法做到这一点。

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

这是声明:

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();
}
4

5 回答 5

32

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

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 */
    );

愿它有所帮助。

于 2014-11-13T12:45:57.457 回答
14

我有同样的问题。我的解决方案是这样的:

确保您的活动实现 onBackStackChangedListener。在你的活动的 onCreate 我设置了后台监听器并设置了工具栏

@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();
}
于 2015-01-08T16:50:35.617 回答
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>

工具栏.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>

抽屉.java

包 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;
    }

}
于 2014-11-12T05:12:47.937 回答
2

@hata 的答案在大多数情况下都是正确的。

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

当然,如果您使用的是股票Toolbar AppCompatActivity提供的股票,那么这样做是没有意义的,比如股票Theme.AppCompat.Light根主题。即使您想要Toolbar在您的布局中自定义,例如,如果您正在实现 Material Design 的 over-toolbar-under-statusbar Navigation Drawer 模式,您仍然可以调用setSupportActionBar(toolbar)并且仍然不传递工具栏ActionBarDrawerToggle()让活动处理导航图标。

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

问题是,当您不将工具栏作为第四个参数传递时,活动应该提供导航图标(箭头)——并AppCompatActivity返回homeAsUpIndicator属性值——它在任一标准 AppCompat 主题中定义。

但是,当您显式传递 , 时ToolbarActionBarDrawerToggle期望工具栏实例提供可绘制的导航指示器——但事实并非如此,因为即使您像这样对其应用适当的样式:

<android.support.v7.widget.Toolbar
        ...
        app:theme="?actionBarTheme"
        style="@style/Widget.AppCompat.Toolbar">

出于某种原因(也许它甚至是一个错误),Widget.AppCompat.Toolbar样式没有navigationIcon属性,因此在询问导航图标时Toolbar返回。因此,为了解决这个问题,您只需从样式派生并添加属性:nullActionBarDrawerToggle

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

现在,您可以使用工具栏感知构造函数ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, 0, 0),并且仍然保留导航图标。

于 2015-06-16T20:48:00.323 回答
1

此行确保汉堡图标在单击时更改为箭头。确保你在你的代码中写了这个。

mDrawerLayout.setDrawerListener(mDrawerToggle);
于 2015-03-02T12:07:49.067 回答