在TextView中设置文本时,应用崩溃

时间:2019-11-03 00:37:35

标签: android android-intent textview

XML代码

  

android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="192dp"
android:background="@color/colorPrimaryDark"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
android:gravity="bottom"
android:id="@+id/nav_header">

<TextView
    android:id="@+id/user_Name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="20dp"
    android:layout_marginBottom="8dp"
    android:textSize="20dp"
    android:textColor="@android:color/white"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1"/>

*** java代码

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    btn2 = findViewById(R.id.button);
    TextView textView = findViewById(R.id.user_Name);
    textView.setText("My text");
}

当我使用此代码设置Text时,应用崩溃,空指针异常

1 个答案:

答案 0 :(得分:0)

您不能直接访问导航抽屉标题

执行此操作:

 NavigationView navigationView = findViewById(R.id.your_navigation_drawer_id);
 View navHeaderView = navigationView.getHeaderView(0);

 TextView textView = navHeaderView.findViewById(R.id.user_Name);
 textView.setText("My text");