Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback after all child Views from XML have been added to ViewGroup?

I was writing a custom ViewGroup and came across the following problem:

The ViewGroup should be usable by specifying properties in XML only. However, I want to do some internal initialization in code after the ViewGroup has been created and all its child Views from XML have been added (that is, when the layout inflator has added all the child Views of a ViewGroup specified in XML).

All I found related to this are recommendations to use getViewTreeObserver().addOnGlobalLayoutListener(...). However, this is called at least after each child View is added and also after resuming an app etc. So it does not even make it possible to detect the moment when all child Views have been added.

Is there a method called after all child Views have been added to a ViewGroup?

Related: When are child views added to Layout/ViewGroup from XML

like image 233
user905686 Avatar asked Oct 21 '16 18:10

user905686


People also ask

What is ViewGroup?

ViewGroup is a collection of Views(TextView, EditText, ListView, etc..), somewhat like a container. A View object is a component of the user interface (UI) like a button or a text box, and it's also called a widget.

Which of the following are ViewGroup?

Android contains the following commonly used ViewGroup subclasses: LinearLayout. RelativeLayout. ListView.

What is view and ViewGroup in Android Studio?

View is a basic building block of UI (User Interface) in android. A view is a small rectangular box which responds to user inputs. Eg: EditText , Button , CheckBox , etc.. ViewGroup is a invisible container of other views (child views) and other viewgroups.


1 Answers

There is a callback: View.onFinishInflate(). From the documentation (which also has a section "Implementing a Custom View" describing all the callbacks):

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

Simply override the method in your custom ViewGroup:

public class MyViewGroup extends ViewGroup {

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        doMyInitialization();
    }
}
like image 76
user905686 Avatar answered Oct 10 '22 00:10

user905686