2016-09-26 98 views
0

我目前在我的应用程序中使用NavigationView实施了导航抽屉。抽屉的布局分为标题drawer_header.xml和菜单drawer_menu.xml。它看起来是这样的:在导航抽屉标题中添加TextView项目的代码

Drawer

我试图使用setText代替xml但是我收到以下错误,在Java代码中头设置用户名DrawerNameTv

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

这里的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开发新手。

+0

您没有在XML文件中添加文本视图“DrawerNameTv” – Praveen

+0

检查我的更新答案 –

回答

0

视图DrawerNameTv没有在你指的布局中,这就是为什么它给你一个NullPointerException。您需要像这样在NavigationView内找到DrawerNameTv

里面你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"); 
+0

请检查更新后的答案。您需要更改“NavigationView”变量的名称。在NavigationView类中调用了getHeaderView函数。再次检查答案并相应地做出更改。如果有帮助,请回复并接受并点赞。 –

+0

谢谢,我的结尾有一个错字。这个解决方案奇妙地工作。队友的欢呼声! – aurelio

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; 
      } 
+0

它不回答这个问题。为什么它得到upvote? –