【发布时间】:2021-09-15 20:05:52
【问题描述】:
findViewById 在“mImageView”和“mCropOverlayView”的自定义视图中返回“null”。
public class CropImageView extends FrameLayout {
private ImageView mImageView;
private CropOverlayView mCropOverlayView;
public CropImageView(@NonNull Context context) {
super(context);
init(context);
}
public CropImageView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public CropImageView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
View view = inflate(getContext(), R.layout.crop_image_view, this);
mImageView = view.findViewById(R.id.img_crop);
mCropOverlayView = view.findViewById(R.id.overlay_crop);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
public void setImageBitmap(Bitmap bitmap) {
mImageView.setImageBitmap(bitmap);
mCropOverlayView.setBitmap(bitmap);
}
public void crop(CropListener listener, boolean needStretch) {
if (listener == null)
return;
mCropOverlayView.crop(listener, needStretch);
}
}
这是我试图在我的自定义视图中扩展的自定义视图的 XML 文件。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/img_crop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="fitCenter" />
<com.wildma.idcardcamera.cropper.CropOverlayView
android:id="@+id/overlay_crop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignBottom="@+id/img_crop" />
</RelativeLayout>
【问题讨论】:
-
这段代码根本无法编译。你在调用什么 inflate() ?它不是 FrameLayout 的函数,您也不会在 LayoutInflater 上调用它。
-
@GabeSechan - 可能是
LayoutInflater.inflate静态导入? -
@MarkKeen 不,LayoutInflater 没有静态膨胀功能。参数也会出错(它们都没有将上下文作为第一个参数,因为上下文是在构造函数中传递的)。
-
@GabeSechan inflate 是 View 的静态方法。见developer.android.com/reference/android/view/…
标签: java android xml android-custom-view