Android中导航视图的标题视图实例始终为null

时间:2016-03-21 22:32:55

标签: android android-navigation-drawer android-navigationview

我正在开发一款Android应用。在我的应用程序中,我正在使用导航视图。我需要根据情况以编程方式更改标题视图的设计。但是标头视图实例的变量总是抛出空异常。我的代码出了什么问题?

这就是我在导航视图中设置标题视图的方法

<android.support.design.widget.NavigationView
        app:itemIconTint="@drawable/drawer_item"
        app:itemTextColor="@drawable/drawer_item"
        android:id="@+id/left_nv_view"
        app:headerLayout="@layout/header_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start" />

这是我的标题视图的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/header_view"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content">

</LinearLayout>

这是我实例化标题视图并在活动

中对其进行更改的方法
  //I initialized navigation drawer and navigation view first 
   headerView = (LinearLayout)findViewById(R.id.header_view);
   headerView.setOrientation(LinearLayout.VERTICAL);

但它总是抛出空指针异常。我该如何修复我的代码?

1 个答案:

答案 0 :(得分:1)

NavigationView需要一些时间才能使其标题View膨胀并布局。通常,只有在onCreate()完成后才会完成此操作,但您可以使用NavigationView#getHeaderView()方法立即强制执行此操作。

成功加载标题后,您就可以在Activity View层次结构中找到它们,并且您对findViewById()的调用将不会; t返回null。

相关问题