我需要从片段更改NavigationView标题图像,但我得到错误。有人可以告诉我我做错了什么?。谢谢你的帮助)))
java.lang.NullPointerException:尝试对空对象引用调用虚拟方法“android.view.查看android.support.design.widget.导航视图.getHeaderView(int)”
- 我的片段代码 *
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
NavigationView navigationView = (NavigationView) view.findViewById(R.id.nav_view);
//ERROR
View headerView = (NavigationView) navigationView.getHeaderView(0);
ImageView drawerImage = (ImageView) headerView.findViewById(R.id.header_image);
drawerImage.setImageResource(R.drawable.header_img2);
getActivity().setTitle("Our Projects");
super.onViewCreated(view, savedInstanceState);
}
- 导航标头xml*
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:id="@+id/navigation_header"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="@+id/header_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/header_img1" />
<ImageView
android:id="@+id/header_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:layout_gravity="center"
android:scaleType="fitStart"
app:srcCompat="@drawable/logo" />
</FrameLayout>
- 活动_主要 *
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<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:background="@color/colorWhite"
android:clickable="false"
app:headerLayout="@layout/nav_header_main"
app:itemIconTint="@color/colorPrimary"
app:itemTextColor="@color/colorPrimary"
app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
4条答案
按热度按时间jum4pzuy1#
您在这里引用的视图是您的片段,它不是导航抽屉的容器
4sup72z82#
kmbjn2e33#
像这样使用
findViewById
;vsdwdz234#