我正在使用导航抽屉的navigationView布局,如下所示:
activity_main.xml:
*e &&
正如您所看到的那样,应用了一个标题布局(nav_drawer_header_layout),在该布局中有一个我想要放置大图像的图像视图。
MainActivity.java:
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/nav_menu"
app:headerLayout="@layout/nav_drawer_header_layout"
android:background="@color/colour8"/>
然后我收到以下logcat错误:
//Initailise the navigation view
NavigationView navView = (NavigationView)findViewById(R.id.navigation_view);
//Cast the imageView holder that the large is placed in
ImageView header = (ImageView)findViewById(R.id.header_navigation_drawer_header_image);
//Dimensions
int imageViewWidth = header.getWidth();
int imageViewHeight = header.getHeight();
//Scale image into header with picasso
Picasso.with(this).load(R.drawable.food)
.fit()
.centerCrop()
.resize(imageViewWidth,imageViewHeight)
.into(header);
问题似乎是imageView为null,
解释与解释将非常感谢.... 感谢您的帮助!!!!
答案 0 :(得分:0)
删除app:headerLayout
中的NavigationView
属性,如:
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/nav_menu"
android:background="@color/colour8"/>
然后在Activity
中夸大标题布局,例如:
//you can use LinearLayout, RelativeLayout ,FrameLayout etc. which you are using in your header layout
LinearLayout headerLayout = navigationView.inflateHeaderView(R.layout.nav_drawer_header_layout);
现在,您可以在标题布局中获得View
,例如:
ImageView header = (ImageView)headerLayout .findViewById(R.id.header_navigation_drawer_header_image);
您收到
IllegalArgumentException : Target must not be null
,表示您的ImageView
为空。因为它不在Activity
的布局中。它位于NavigationView
的布局中。
答案 1 :(得分:0)
将此代码替换为
//Cast the imageView holder that the large is placed in
ImageView header = (ImageView)findViewById(R.id.header_navigation_drawer_header_image);
此
//Initailise the navigation view
NavigationView navView = (NavigationView)findViewById(R.id.navigation_view);
//Cast the imageView holder that the large is placed in
ImageView header = (ImageView) navView.findViewById(R.id.header_navigation_drawer_header_image);
这是因为你的图像视图在navView片段里面,android打算在你的布局中找到你的布局元素但是里面没有imageView因此它返回null所以必须说明在哪里找到这个navView.findViewByID()
的视图。