I have a DrawerLayout which wraps a NavigationView with a header layout. The XML is below:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/drawer"/>
</android.support.v4.widget.DrawerLayout>
The headerLayout is a LinearLayout which wraps a ImageView, below is drawer_header.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="@color/blue_primary"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="120dp"
android:id="@+id/ivDrawerUserFace"
android:layout_height="120dp" />
</LinearLayout>
I don't know why I can't find the ImageView by findViewById(R.id.ivDrawerUserFace), which returns null instead. However, I am able to find it by the following code:
ViewGroup headerView = (ViewGroup) mNavigationView.getHeaderView(0);
ImageView faceView = (ImageView) headerView.getChildAt(0); // faceView is not null
String faceUrl = QingUApp.getInstance().getFaceUrl();
if (faceUrl != null) {
Glide.with(this).load(faceUrl).into(faceView);
}
View viewById = findViewById(R.id.ivDrawerUserFace); // viewById is null
I have called setContentView() before the above code. And Glide loads the image into the ImageView successfully. Why can't I find it by findViewById()?
I guess it's because the image view isn't within the XML file passed to setContentView(). However, I could get the view by findViewById() in the same Activity with code like this:
private LoaderManager.LoaderCallbacks<Bitmap> mUserFaceLoaderCallbacks = new LoaderManager.LoaderCallbacks<Bitmap>() {
@Override
public Loader<Bitmap> onCreateLoader(int i, Bundle bundle) {
return new UserFaceLoader(NewQingUActivity.this, mFaceUrl);
}
@Override
public void onLoadFinished(Loader<Bitmap> loader, Bitmap bitmap) {
if (bitmap != null) {
ImageView ivUserFace = (ImageView) findViewById(R.id.ivDrawerUserFace);
ivUserFace.setImageBitmap(bitmap);
}
}
@Override
public void onLoaderReset(Loader<Bitmap> loader) {
}
};