通过操作栏标题切换导航抽屉。

9
我正在尝试让用户通过点击操作栏标题(这是当前Android Gmail应用程序的设置方式)来打开/关闭应用程序中的导航抽屉。目前,用户可以通过点击应用程序/抽屉图标或左右滑动来切换抽屉。然而,操作栏标题本身不可点击。根据开发文档,当我们使用NAVIGATION_MODE_STANDARD时,点击操作栏标题应该“将onOptionsItemSelected分派给具有android.R.id.home项目ID的菜单项的主机Activity”,但出于某种原因我无法让标题以这种方式工作。
我相信导航抽屉本身没有问题,但以下是我如何设置操作栏:
private void configureActionBar(CharSequence mTitle) {

    ActionBar actionBar = getActionBar();

    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    actionBar.setIcon(R.drawable.ic_blank);

    GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM,
                new int[] {
                0xFF004700, 0xFF002900
                });

    gd.setCornerRadius(0f);

    actionBar.setBackgroundDrawable(gd);

    // set the title of the action bar using the given title
    actionBar.setTitle(mTitle);

}

任何建议都将不胜感激!
2个回答

24
如果您希望通过点击ActionBar的图标/标题来打开抽屉,我建议您使用支持库中提供的ActionBarDrawerToggle类(android.support.v4.app.ActionBarDrawerToggle)。请注意,保留HTML标签。

Reference: https://developer.android.com/reference/android/support/v4/app/ActionBarDrawerToggle.html

使用示例:
https://developer.android.com/training/implementing-navigation/nav-drawer.html

当在onOptionsItemSelected()中捕获事件时,关键是要将其传递给ActionBarDrawerToggle,以便它可以处理打开/关闭抽屉请求:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Pass the event to ActionBarDrawerToggle, if it returns
    // true, then it has handled the app icon touch event
    if (mDrawerToggle.onOptionsItemSelected(item)) {
      return true;
    }
    // Handle your other action bar items...

    return super.onOptionsItemSelected(item);
}

谢谢您的帖子 - 我已经按照您所述将事件传递给了mDrawerToggle(这就是为什么点击应用程序图标会像预期的那样切换抽屉),但我在从ActionBar标题(与Gmail应用程序中的图标分开)获得相同功能方面遇到了麻烦。我想可能可以使用自定义视图作为ActionBar的标题,其中TextView作为标题 - 然后我可以为该视图设置一个onClick监听器并调用openDrawer(),但这似乎不如我希望找到的解决方案优雅。谢谢! - David Crozier
嗯,奇怪的是,我正在开发的当前应用程序也适用于标题。实际上,图标+标题就像一个按钮,因为无论我点击哪个都会突出显示。也许使用ActionBarDrawerToggle(来自支持库)与ActionBar(不是来自支持库)存在问题。尝试使用来自支持库的ActionBar?你需要使用getSupportActionBar()而不是getActionBar()...只是猜测。 - nsL
啊,好发现。我一直没有使用SupportActionBar,所以我一定会尝试它。谢谢! - David Crozier
@DSCroz,请在答案对您有所帮助时接受它为正确答案!谢谢。 - nsL

0

如果在 AndroidManifest.xml 中设置了应用程序主题属性,那么图标/标题将会显示:

    <application
    android:name=".SampleApp"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">

res/values/styles.xml 包含主题声明

<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">

它通过使用android.support.v7.app.ActionBarDrawerToggle来实现,同时支持v4类已被弃用。请参见如何使用support-v7-appcompat库


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