การใช้ NavigationView จากไลบรารีการออกแบบที่รองรับ Android ที่เพิ่งเปิดตัว หากเค้าโครงส่วนหัวการนำทางมี 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()
) ทำงานได้ดี ปัญหาคือเมื่อมีการคลิกส่วนหัว:
Drawer_header.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 สามารถใช้ไฟล์ทรัพยากรเมนูมาตรฐานได้ แต่มีปัญหาคล้ายกันหากใช้ onClick จากทรัพยากร XML ของเมนู ตามการอ้างอิงทรัพยากรเมนู แอตทริบิวต์ 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
อัปเดต
ฉันทดสอบ xml onClick โดยใช้โปรเจ็กต์สาธิต "อย่างเป็นทางการ" สำหรับไลบรารีการออกแบบ Android ผลลัพธ์เดียวกัน: การเพิ่ม onClick (เป็น xml) ลงในเมนูหรือส่วนหัวของ NavigationView ทำให้แอปขัดข้อง ดูเหมือนว่าจะเป็นข้อบกพร่องของ NavigationView
แก้ไขแล้วในเวอร์ชัน 23.1
Google เปิดตัวการแก้ไขสำหรับข้อผิดพลาด XML onClick เหล่านี้ใน Support Library v23 .1.