Android How to - Get Activity from ViewParent








Question

We would like to know how to get Activity from ViewParent.

Answer

/*  ww  w .  j ava2s.c  o  m*/
import android.app.Activity;
import android.view.ViewParent;

class ActivityUtils {

  /**
   * Return the {@link Activity} of {@link ViewParent}.
   * 
   * @param parent
   * @return
   */
  public final static Activity getActivity(ViewParent parent) {
    if (parent instanceof Activity) {
      return (Activity) parent;
    }
    if (parent.getParent() != null) {
      return getActivity(parent.getParent());
    }
    return null;
  }
}