直接通过findViewById获取NavigationView中控件引用为null的问题
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<!--主界面-->
<include
layout="@layout/app_bar_home"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!--菜单-->
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_home"
app:menu="@menu/activity_home_drawer" />
</android.support.v4.widget.DrawerLayout>
以上的布局就是我遇到问题的那个Activity的布局样式,使用了NavigationView这个控件,当我想要获取nav_header_home这个布局中的控件的时候,理所当然的直接使用findViewById()的方式去获取,得到的结果出乎意料竟然是null!!!
所以!NavigationView中Header部分的控件不能直接通过findViewById获取,需要先通过getHeaderView这个方法获取到nav_header_home这个布局所对应的View,这个对应的下标为0,下面是正确的方式获取控件的代码:
View view = navigationView.getHeaderView(0)
RelativeLayout rl_nav_header = (RelativeLayout) view.findViewById(R.id.rl_nav_header);