How do I get Activity Context in FloatWindow with Button OnClickListener

1.1k views Asked by At

I have a FloatWindow,it has a static method with view.Button OnClickListener, I want Show Dialog in any Activity When I Click the View,But the Context can't not used the getApplicationContext, it will Show "Unable to add window token null is not for an application", So How do I get the Activity context when I Click the View?

//the Para is getapplicationcontext,but is not work 

public static void createStatusWindow(Context context) {

        WindowManager windowManager = getWindowManager(context);
        int screenWidth = windowManager.getDefaultDisplay().getWidth();
        int screenHeight = windowManager.getDefaultDisplay().getHeight();

        if (statusWindow == null) {
            LayoutInflater mInflater = LayoutInflater.from(context);
            statusWindow = mInflater.inflate(R.layout.floatwindow, null);
            statusWindow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
       MessageBox.show("GPS Status", "Good", MessageBox.Icon.Alert,context,true);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
   }
2

There are 2 answers

1
Galax On

try using yourActivityName.this in place of getApplicationContext()

2
blueware On

You can make a reference from your activity and then pass it to your createStatusWindow method:

public class YourActivity extends Activity{

private YourActivity mContext;

@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        mContext = this;
        createStatusWindow(mContext);

}

Now change the context variable in your createStatusWindow method to final as follows:

public static void createStatusWindow(final Context context) {

        WindowManager windowManager = getWindowManager(context);
        int screenWidth = windowManager.getDefaultDisplay().getWidth();
        int screenHeight = windowManager.getDefaultDisplay().getHeight();

        if (statusWindow == null) {
            LayoutInflater mInflater = LayoutInflater.from(context);
            statusWindow = mInflater.inflate(R.layout.floatwindow, null);
            statusWindow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
       MessageBox.show("GPS Status", "Good", MessageBox.Icon.Alert,context,true);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
   }

It will work.