直接通过findViewById获取NavigationView中控件引用为null的问题

直接通过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);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值