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

陌路散爱 提交于 2019-12-23 15:12:27

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/40183648/callback-after-all-child-views-from-xml-have-been-added-to-viewgroup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!