MaterialNavigationDrawer常见8大坑与解决方案:Fragment混用、主题冲突等避坑清单
MaterialNavigationDrawer常见8大坑与解决方案:Fragment混用、主题冲突等避坑清单
MaterialNavigationDrawer 是一个让 Android 应用快速拥有 Material Design 风格 Navigation Drawer(抽屉式导航)的开源 Activity 库,封装了账号切换、多 Section、底部 Section 等复杂交互。但它的"坑"也很集中:Fragment 混用直接崩溃、主题配置不对抽屉头就失效、首次启动抽屉自动打开……本文结合源码,逐一拆解新手最常踩的 8 大坑及解决方案。
坑1:两种 Fragment 混用,直接抛 RuntimeException
这是最经典的坑。库同时兼容 android.app.Fragment 和 android.support.v4.app.Fragment,但同一个 Activity 内只允许用其中一种,混用会直接崩溃:
RuntimeException: You should use only one type of Fragment
判断逻辑在 MaterialNavigationDrawer.java:
else if (fragment instanceof android.app.Fragment) {
if (oldFragment instanceof android.support.v4.app.Fragment)
throw new RuntimeException("You should use only one type of Fragment");
解决方案:项目统一用 support v4 的 Fragment(新项目基本都会),newSection() 里传入的 Fragment 类型保持全局一致即可,不要一部分继承 Fragment、另一部分继承 android.support.v4.app.Fragment。
坑2:在 Activity 里调用 setContentView() 必崩
MaterialNavigationDrawer 自己管理整个界面布局(Toolbar + 内容区 + 抽屉),不允许你再调用 setContentView(),三种重载都会主动抛异常:
RuntimeException: The library have it's own content, please move all content inside section's fragments
见 MaterialNavigationDrawer.java。
解决方案:所有页面内容都放进 Section 对应的 Fragment 里,Activity 本身只负责重写 init(Bundle) 方法注册 Section,参考示例 MockedAccount.java:
public class MockedAccount extends MaterialNavigationDrawer {
@Override
public void init(Bundle savedInstanceState) {
this.addSection(newSection("Section 1", new FragmentIndex()));
this.addBottomSection(newSection("Bottom Section", R.drawable.ic_settings_black_24dp,
new Intent(this, Settings.class)));
}
}
坑3:init() 里一个 Section 都没加
init() 执行完库会做强制校验,一个顶层 Section 都没有时直接崩溃:
RuntimeException: You must add at least one Section to top list.
见 MaterialNavigationDrawer.java。
解决方案:init() 里至少 addSection() 一个条目。注意 addBottomSection()(底部区)不能单独存在,它不参与"至少一个"的计数。
坑4:主题冲突——Activity 没用 MaterialNavigationDrawerTheme
这是最隐蔽的坑。抽屉头类型、抽屉颜色、默认 Section 等全部通过主题属性解析(drawerType、drawerColor、colorPrimary 等)。如果你的 Activity 直接套了普通的 Theme.AppCompat 而不是 MaterialNavigationDrawerTheme 家族,这些属性全部解析失败,表现为:抽屉头变成默认账号样式、colorPrimary 取不到导致工具栏颜色异常。
主题定义在 themes.xml,标准写法是继承库主题再覆盖颜色,示例项目 styles.xml 与 AndroidManifest.xml:
<style name="MockedAccountLight" parent="MaterialNavigationDrawerTheme.Light.DarkActionBar">
<item name="colorPrimary">#8bc34a</item>
<item name="colorPrimaryDark">#558b2f</item>
<item name="singleAccount">true</item>
</style>
解决方案:每个继承 MaterialNavigationDrawer 的 Activity 都在 Manifest 中指定一个 parent="MaterialNavigationDrawerTheme*" 的主题,且 colorPrimary / colorPrimaryDark 必须自己提供,否则工具栏和状态栏颜色不可控。
坑5:drawerType 与头设置方法不匹配
drawerType 有 4 种取值:DRAWERTYPE_ACCOUNTS(账号)、DRAWERTYPE_IMAGE(图片头)、DRAWERTYPE_CUSTOM(自定义头)、DRAWERTYPE_NO_HEADER(无头)。每个设置方法都会校验当前类型,不匹配就抛异常:
| 你调用的方法 | 要求的 drawerType | 报错信息 |
|---|---|---|
setDrawerHeaderCustom() |
CUSTOM | Your header is not setted to Custom, check in your styles.xml |
setDrawerHeaderImage() |
ACCOUNTS 或 IMAGE | Your drawer configuration don't support a background image |
addAccount() / setUsername() |
ACCOUNTS | Your header is not setted to Accounts |
见 MaterialNavigationDrawer.java。
解决方案:改抽屉头类型时,主题(drawerType)和 Java 代码(对应的 set 方法)要成对修改,不要只改一头。
坑6:每次启动抽屉都自动打开
库内置了"教学模式"(learning pattern):首次启动时自动把抽屉滑开展示导航。但它有一个 private static 标志位(见 MaterialNavigationDrawer.java),且只要主题没显式关闭,行为就会让新手困惑——尤其做自动化测试时抽屉挡住操作。
解决方案(二选一):
- 主题中加
<item name="learningPattern">false</item>(见示例 styles.xml) - 代码中调用
disableLearningPattern()
坑7:主/子页面用错 setFragment 或返回键行为不符合预期
主页面(Section 对应的 Fragment)和二级页(子 Fragment)有两套方法:
setFragment(fragment, title):替换主内容,重置子页栈setFragmentChild(fragment, title):压入子页栈,工具栏箭头变为"返回",见 MaterialNavigationDrawer.java
子页里误用 setFragment 会清掉整个导航栈,导致返回键直接退出。另外返回键本身有 3 种模式,默认是 BACKPATTERN_BACK_ANYWHERE(按返回直接退出):
setBackPattern(MaterialNavigationDrawer.BACKPATTERN_BACK_TO_FIRST); // 返回回到第一个 Section
setBackPattern(MaterialNavigationDrawer.BACKPATTERN_CUSTOM); // 自定义,需重写 backToSection()
BACKPATTERN_CUSTOM 模式下重写 backToSection() 时必须返回一个以 Fragment 为目标的 Section,否则抛异常。示例可看 MasterChildActivity.java。
解决方案:二级页面一律 setFragmentChild;想"返回先回首页再退出"就用 BACK_TO_FIRST;箭头图标用 setHomeAsUpIndicator(),注意官方注释要求在 init() 之后调用。
坑8:平板双栏(Multipane)在手机上永远不生效
开启 multipaneSupport 后预期是"抽屉常驻左侧 + 右侧内容"的双栏布局(如上文截图),但实际生效条件非常苛刻——三个条件必须同时满足,见 deviceSupportMultiPane():
- 主题中
multipaneSupport为true - 设备必须是平板(
isTablet()) - 当前方向必须是横屏
手机上测、或平板竖屏测,都会退回普通抽屉 + 汉堡按钮模式。
解决方案:功能验证请使用平板并横屏测试;onResume() 中库会自动根据当前配置切换锁定/解锁抽屉(L757-L763),不要自行覆盖 onResume 破坏该逻辑。
附:启动时 Section 校验的两个高频报错
最后补充一个与"默认 Section"相关的连环坑,defaultSectionLoaded 配置错了启动即崩:
- 索引越界:
You are trying to open at startup a section that does not exist - 首个 Section 的目标不是 Fragment:
The first section added must have a fragment as target(Intent / Listener 目标不能当默认页)
见 MaterialNavigationDrawer.java。
8大坑速查清单
| # | 坑 | 解决一句话 |
|---|---|---|
| 1 | Fragment 混用崩溃 | 全项目统一用 v4 Fragment |
| 2 | 调用 setContentView | 内容全放 Fragment,Activity 只写 init() |
| 3 | 没加 Section | init() 至少 addSection 一个 |
| 4 | 主题冲突 | Activity 必须用 MaterialNavigationDrawerTheme 家族 |
| 5 | drawerType 不匹配 | 主题与 set 方法成对修改 |
| 6 | 抽屉自动打开 | learningPattern 设 false |
| 7 | 返回行为不对 | 子页用 setFragmentChild + 选对 BackPattern |
| 8 | 双栏不生效 | 平板 + 横屏 + multipaneSupport 三者缺一不可 |
掌握以上 8 点,MaterialNavigationDrawer 的基本使用就没什么障碍了。更多细节建议直接阅读示例目录 MaterialNavigationDrawer/app/src/main/java/it/neokree/example/ 下的各功能演示 Activity,每个"坑"对应的正确姿势都有现成范例。
