Home > front end >  findViewById returns "null" in a custom view
findViewById returns "null" in a custom view

Time:09-16

findViewById is returning "null" in a custom view for "mImageView" & "mCropOverlayView".

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);
}

}

And here is my XML file for the custom view which I am trying to inflate in my custom view.

<?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>

CodePudding user response:

Hello @Syed Arsalan Kazmi

I created a demo to test your question quickly, the value of findViewById() is not null. The screenshot: http://prntscr.com/1sdnvuh

Dev Environment: Android Studio 4.2.2, Android support lib, SDK 30

  1. Your code can be compiled.
  2. It's better to read and try to practice the demo of the lib you used.(maybe you have a new idea) https://github.com/wildma/IDCardCamera/blob/master/README_EN.md https://github.com/wildma/IDCardCamera/tree/master/app

CodePudding user response:

What happens is that inflate() does not attach the inflated view, and if the last parameter is not null, it return that value. The simpliest fix is to pass null instead of this:

View view = inflate(getContext(), R.layout.crop_image_view, null);

The returned view will be RelativeLayout. You will probably want to add it to your view hierarchy:

   addView(view);
  • Related