在Navigation Drawer标题中添加TextView项的代码

时间:2016-09-26 09:38:33

标签: java android xml android-studio

我目前使用NavigationView在我的应用内部实现了导航抽屉。抽屉的布局分为标题drawer_header.xml和菜单drawer_menu.xml。它看起来像这样:

Drawer

我正在尝试使用DrawerNameTv而不是setText在java代码的标头中设置用户名xml但是我收到以下错误:

  

java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.widget.TextView.setText(java.lang.CharSequence)'

这是Main_Activity.java

TextView DrawerName;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    CustomToolbar = (Toolbar) findViewById(R.id.toolbar);
    DrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    NavigationView = (NavigationView) findViewById(R.id.navigation_view);
    DrawerName = (TextView) findViewById(R.id.DrawerNameTv);

    DrawerName.setText("Test");

    ...

drawer_header.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/user_pic" />

    <TextView
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:textSize="20dp"
        android:layout_marginTop="120dp"
        android:id="@+id/DrawerNameTv" />

</RelativeLayout>

请原谅我,因为我是Android开发的新手。

2 个答案:

答案 0 :(得分:0)

在课堂上添加以下功能。

public boolean onNavigationItemSelected(MenuItem item) {
   // Handle navigation view item clicks here.
   int id = item.getItemId();

    switch(id){
        case R.id.nav_home:
             // call your page from here
             break;
       case R.id.nav_message:
             // call your page from here
             break;
      case R.id.nav_setting:
             // call your page from here
             break;
    }

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                drawer.closeDrawer(GravityCompat.START);
                return true;
            }

答案 1 :(得分:0)

在您所指的布局中找不到视图DrawerNameTv,这就是为什么它会为您提供NullPointerException。您需要在此DrawerNameTv内找到NavigationView

onCreate功能

// lets change the variable names first.
private NavigationView mNavigationView;

mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
DrawerName = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.DrawerNameTv);

// Now set the text here
DrawerName.setText("Test");