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

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

}