我目前在我的应用程序中使用NavigationView
实施了导航抽屉。抽屉的布局分为标题drawer_header.xml
和菜单drawer_menu.xml
。它看起来是这样的:在导航抽屉标题中添加TextView项目的代码
我试图使用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开发新手。
您没有在XML文件中添加文本视图“DrawerNameTv” – Praveen
检查我的更新答案 –