Android:我需要在onClickListener上设置Drawer“burger icon”吗?

时间:2015-06-11 15:45:21

标签: android android-actionbar navigation-drawer

我尝试使用抽屉和工具栏/操作栏设置活动,但我在设置方面遇到了一些问题。

我的 main_activity.xml

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:elevation="7dp”>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

    <FrameLayout
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/main_tool_bar"/>
</RelativeLayout>
<!--... the rest of my layout for the drawer...-->

我的toolbar.xml:

  <android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/toolbar_color"/>

的活动:

public class MainActivity extends ActionBarActivity {

private void setupToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.main_tool_bar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_menu_white);
        toolbar.setTitle(getResources().getString(R.string.to_sign));

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawerLayout.openDrawer(Gravity.LEFT);
            }
        });

        setActionBarTextColor(Color.WHITE);
}


    //........ more code not related with bar or drawer.........

}

我希望能够在不使用XML配置(主题)的情况下更改背景颜色,文本颜色和图标(导航汉堡或任何其他图标)。

据我所知,setSupportActionBar(工具栏)会为我实现clickListener。但是当我没有指定监听器时,按钮根本不起作用(根本没有动作)。

1 个答案:

答案 0 :(得分:1)

通常情况下,您会使用抽屉听众聆听抽屉的开/关事件。创建此侦听器时,您可以指定工具栏,然后按钮将起作用。

public void setUp(int fragmentId, DrawerLayout drawerLayout) {
    ...
    mDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, getToolbar(),
            R.string.navigation_drawer_open, R.string.navigation_drawer_close) {

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
        }

    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Forward the new configuration the drawer toggle component.
    mDrawerToggle.onConfigurationChanged(newConfig);
}

当然,您可以选择不覆盖这些方法,只使用普通的ActionBarDrawerToggle对象。

这是(大部分)使用抽屉创建活动时默认情况下在AndroidStudio中生成的代码,因此我将其视为最佳做法。