Search code examples
androidandroid-layoutandroid-viewandroid-custom-view

Notification on View added to parent?


When I build a View in Android dynamically I have to add it to a "parent" ViewGroup by calling

myLinearLayout.addView(myView);

I know that I can supervise the ViewGroup for any children to be added via the excellent onHierarchyChangeListener, but in my case I need the feedback in the View itself. Therefore my question is:

Is there something like a View.onAddedToParent() callback or a listener that I can build on?

To make things very clear: I want the view to handle everything on its own, I am aware of the fact that I could catch the event in the "parent" and then notify the view about things, but this is not desired here. I can only alter the view

Edit: I just found onAttachStateChangeListener and it would seem to work for most situations, but I'm wondering if this is really the correct solution. I'm thinking a View might just as well be passed on from one ViewGroup to another without being detached from the window. So I would not receive an event even though I want to. Could you please elaborate on this if you have insight?

Thanks in advance


Solution

  • You can create custom view and do your stuff in its onAttachedToWindow

    public class CustomView extends View {
    
       public CustomView(Context context) {
           super(context);
       }
    
       @Override
       protected void onAttachedToWindow() {
           super.onAttachedToWindow();
           Log.d("CustomView", "onAttachedToWindow called for " + getId());
           Toast.makeText(getContext(), "added", 1000).show();
       }
    }
    

    If you want to ensure that your customview added to correct viewgroup which you want

    @Override
     protected void onAttachedToWindow() {
        // TODO Auto-generated method stub
        super.onAttachedToWindow();
    
        if(((View)getParent()).getId()== R.id.relativelayout2)
        {           
            Log.d("CustomView","onAttachedToWindow called for " + getId());
            Toast.makeText(context, "added", 1000).show();          
        }
    
    }