Skip to content Skip to sidebar Skip to footer

Custom View Hierarchy Child Not Added

I have a hierarchy of custom views that looks like this: Activity(RelativeLayout) -> ParentLayout(FrameLayout) -> ChildLayout(LinearLayout) The activity and parent layout are

Solution 1:

So it looks like when you have a custom view class, you don't want to have the view of the layout file be the same type as the custom class. i.e., if I have ParentLayout.java, I don't want parent_layout.xml's root to be <net.openeye.TouchEvents.ParentLayout>. It seems that when you want both a custom layout file and custom view class, you need to have the view class inflate the layout. If the layout has an element (the root, on this case) that is the same as the class, it will cause infinite recursion as the view inflates the layout, which instantiates the class, which inflates the layout... and so on.

I got this to work finally by making the following changes:

parent_layout.xml: Change the root element from net.openeye.TouchEvents.ParentLayout to the class it extends, FrameLayout. It now looks like this:

<FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><!-- ... --></FrameLayout>

child_layout.xml: Change the root element from net.openeye.TouchEvents.ChildLayout to the class it extends, LinearLayout. It now looks like this:

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="300dp"android:layout_height="300dp"android:orientation="vertical"><!-- ... --></LinearLayout>

ParentLayout.java: Inflate it's layout during instantiation. It now looks like this:

public ParentLayout(Context context) {
    super(context);
    init(context);
}

public ParentLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context);
}

public ParentLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context);
}

private void init(Context context) {
    inflate(context, R.layout.parent_layout, this);
}

ChildLayout.java: Same thing as ParentLayout.java, but inflate child_layout.

After getting this working and thinking about why this is happening, it makes sense that this is how it works.

Post a Comment for "Custom View Hierarchy Child Not Added"