Search code examples
androidandroid-layoutandroid-view

How can a view detect when it's being attached to its parent?


I have a View that needs to detect when it's being attached to its parent view.

In a ViewGroup I have the OnHierarchyChangeListener which allows me to know when a child view is being added / removed, but I need the opposite thing.


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

    [EDIT 1]

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