Custom View – provide layout from XML when children not supplied

I was doing a component based on LinearLayout instantiated from XML. It could contain children provided as sub-tags in the XML or be left empty and then default layout should be loaded from XML file.

Decision about inflating new layout could be based on existence of a view with specific ID

if(findViewById(R.id.my_id) == null) {
    //view with my id doesnt exist
}

or based on children count

if (getChildCount() == 0) {
    //view has no children
}

but when I’ve used this code in the constructor of my component then it was failing. There was not definitive answer as to where you should put such code but looking at the handlers of the View class I’ve found onFinishInflate with following comment:

Finalize inflating a view from XML. This is called as the last phase of inflation, after all child views have been added.

That sounds like the right place, you can use it like this:

@Override
protected void onFinishInflate() {
    super.onFinishInflate();
    if (getChildCount() == 0) {
        inflate(context, R.layout.default_layout, this);
    }
    View myView = findViewById(R.id.my_id);
}
This entry was posted in android, JAVA and tagged , , , . Bookmark the permalink.