get Context from various object - Android android.content

Android examples for android.content:Context

Description

get Context from various object

Demo Code


//package com.java2s;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

public class Main {
    public static Context getContext(Object obj) {
        Context context = null;/*from  w w  w.  j a  va  2s.  c  om*/
        if (obj instanceof Fragment) {
            context = ((Fragment) obj).getActivity();
        } else if (obj instanceof android.support.v4.app.Fragment) {
            context = ((android.support.v4.app.Fragment) obj).getActivity();
        } else if (obj instanceof Activity) {
            context = (Context) obj;
        } else if (obj instanceof ViewGroup) {
            context = ((ViewGroup) obj).getContext();
        } else if (obj instanceof View) {
            context = ((View) obj).getContext();
        }
        return context;
    }
}

Related Tutorials