最近我尝试了一个navigation view
带有header
. 标题包含2 个textview、aname
和email
. 当我尝试通过代码动态设置文本视图时,它会引发空指针异常。
谁能帮我解决这个问题。
导航视图
<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"
app:menu="@menu/activity_home_drawer" />
Navigation_header
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:gravity="bottom"
android:orientation="vertical"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imageView"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:layout_marginLeft="20dp"
android:textColor="@color/colorAccent"
android:text="Welcome"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="@+id/email"
android:layout_below="@+id/title"
android:layout_marginLeft="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="info@rubin.in" />
</RelativeLayout>
MainActivity 中的代码
TextView Title = (TextView)findViewById(R.id.title);
Title.setText("Guest");
TextView Email = (TextView)findViewById(R.id.email);
Email.setText("Guest@email.in");
Logcat 错误
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference