Java 从自定义视图调用findViewById将返回null
我正在创建一个自定义类,它应该以某种方式显示两个图像。以下是我的代码的一些选定部分: 我的XML文件:Java 从自定义视图调用findViewById将返回null,java,android,xml,Java,Android,Xml,我正在创建一个自定义类,它应该以某种方式显示两个图像。以下是我的代码的一些选定部分: 我的XML文件: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" <com.kupol24.app.presentation.v
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
<com.kupol24.app.presentation.view.customViews.MyImageLayout
android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/pattern"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/start_pattern"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"/>
<ImageView
android:id="@+id/logo"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/start_logo"
android:layout_centerInParent="true"
android:layout_centerVertical="true"/>
</com.kupol24.app.presentation.view.customViews.MyImageLayout>
</RelativeLayout>
我遇到的问题是findViewById返回null,而不是给我ImageView。我将如何解决这个问题?多谢各位
我遇到的问题是findViewById返回null,而不是
给我图像视图。我将如何解决这个问题
您不能保证已添加自定义布局的子级。ViewGroup具有回调,正如文档所述,在添加所有子视图之后,它被称为膨胀的最后阶段。覆盖此回调,并将您的
findViewById
调用移动到其中在MyImageLayout()构造函数中传递您的Viwe,并使用patternImage=(ImageView)视图.findViewById(R.id.pattern);建议使用onfinishflate()方法初始化子视图。在调用onfinishflate()
之前,这些视图不存在。
public class MyImageLayout extends RelativeLayout {
private ImageView patternImage, logoImage;
private Bitmap pattern, logo;
public MyImageLayout (Context context, AttributeSet attrs) {
super(context, attrs);
patternImage = (ImageView) findViewById(R.id.pattern);
logoImage = (ImageView) findViewById(R.id.logo);
pattern = ((BitmapDrawable) patternImage.getDrawable()).getBitmap();
logo = ((BitmapDrawable) logoImage.getDrawable()).getBitmap();
pattern = Bitmap.createScaledBitmap(pattern, patternDiameter, patternDiameter, false);
logo = Bitmap.createScaledBitmap(logo, logoDiameter, logoDiameter, false);
}
}