使用新发布的 Android 支持设计库中的 NavigationView,如果导航标题布局包含 onClick(在 xml 中),onClick 事件会使应用程序崩溃。OnClick 可以通过view.onClickListener
(而不是 xml)以编程方式添加,然后单击工作正常。但是由于某种原因,每当使用 xml onClick 时,都会出现错误。
这是我的主要布局:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/mainActivityLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<RelativeLayout
android:id="@+id/mainContentFrame"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="@+id/drawerNavView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/drawer_menu">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
在我的活动中,我的菜单项点击(添加navView.setNavigationItemSelectedListener()
)工作正常。问题是单击标题时:
抽屉头.xml:
...
<View
android:id="@+id/testButton"
android:layout_width="match_parent"
android:layout_height="60dp"
android:onClick="testButtonClick"/>
...
产生以下错误:
java.lang.IllegalStateException: Could not find a method testButtonClick(View)
in the activity class android.view.ContextThemeWrapper for onClick handler
on view class android.view.View with id 'testButton'
更新
NavigationView 可以使用标准的菜单资源文件,但是如果使用菜单 XML 资源中的 onClick 也会出现类似的问题。根据Menu Resource reference,该android:onClick
属性会覆盖正常的回调。这通常可以正常工作,但对于 NavigationView 中的菜单项,它就不行了。相反,它会因以下错误而崩溃:
java.lang.RuntimeException: Unable to start activity ComponentInfo{...}:
android.view.InflateException: Binary XML file line #34:
Error inflating class android.support.design.widget.NavigationView
当我删除 XML onClick 时,错误消失了。
更新
我使用Android 设计库的“官方”演示项目测试了 xml onClick。结果相同:将 onClick(在 xml 中)添加到 NavigationView 的菜单或标题会导致应用程序崩溃。所以这似乎是 NavigationView 的一个错误。
已在 v23.1 中解决
Google在 Support Library v23.1 中发布了针对这些 XML onClick 错误的修复程序。