我有一個DrawerLayout
,它包含一個帶有頁眉佈局的NavigationView
。的XML如下:爲什麼findViewById()在抽屜頭中爲視圖返回null?
<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>
的headerLayout
是LinearLayout
它封裝了ImageView
,下面是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>
我不知道爲什麼我找不到ImageView
通過findViewById(R.id.ivDrawerUserFace)
,這改爲返回null
。但是,我可以通過以下代碼找到它:
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
我在上面的代碼之前調用了setContentView()
。並且Glide
成功將圖像加載到ImageView
中。爲什麼我不能通過findViewById()
找到它?
我想這是因爲圖像視圖不在傳遞給setContentView()
的XML文件中。不過,我能得到通過findViewById()
的觀點在同一Activity
有這樣的代碼:
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) {
}
};
你解決這個問題? :D – Vucko
@Vucko我沒有:) – ProtossShuttle
只是爲了澄清,你是否在嘗試獲取視圖之前設置了內容視圖(即'setContentView()')? – burntblark