直接通过findViewById获取NavigationView中控件引用为null的问题
2017-07-22 11:36
931 查看
直接通过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);
相关文章推荐
- Android通过findViewById()获取控件为NULL
- 关于:findViewById()返回null的问题和如何获取Fragment中的组件
- findViewById获取控件ID时返回Null
- Android中findViewById获取控件返回为空问题怎么解决
- 关于:findViewById()返回null的问题和如何获取Fragment中的组件
- android:通过findViewById试图获取界面元素对象为Null,运行会提示空指针异常
- android中布局文件中的控件通过findviewbyid无法关联的解决方法
- Android中findViewById()获取EditText 空指针问题
- 通过findViewById()方法从layout中获取view并进行相应的转换时提示:"Cannot cast from View to AutoCompleteTextView"的解决办法!(转+自己错误)
- Android中findViewById()h获取EditText 空指针问题
- android中通过辅助类解决findViewById需要对返回值强制类型转换的问题
- Android中通过泛型解决findViewById需要强制类型转换的问题
- findViewById值为null,报nullpointer错误的问题
- Android中findViewById()h获取EditText 空指针问题
- findViewById值为null,报nullpointer错误的问题
- Android使用Fragment,不能得到Fragment内部控件,findViewById()结果是Null--已经解决
- 在自定义控件的过程中犯下的错,在调用有三个参数的构造方法时this(context,null,0);第二个参数为空,在Activity中 findViewById找到对应的控件时
- android中布局文件中的控件通过findviewbyid无法关联的解决方法
- Android中findViewById()h获取EditText 空指针问题
- findViewById值为null,报nullpointer错误的问题