简体   繁体   中英

Calling findViewById from custom view returns null

I am making a custom class that is supposed to display two images in a certain way. Here are some selected parts of my code:

My XML file:

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

And the class itself:

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

The problem I get is that the findViewById returns null, instead of giving me the ImageView. How would I solve this issue? Thank you

The problem I get is that the findViewById returns null, instead of giving me the ImageView. How would I solve this issue?

you don't have any assurance that the children of your custom layout have been added. ViewGroup has the onFinishInflate callback, which, as the documentations states, it is called as the last phase of inflation, after all child views have been added. Override this callback, and move your findViewById calls in there

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM