My Activity is trying to create an AlertDialog which requires a Context as a parameter. This works as expected if I use:
AlertDialog.Builder builder = new Al
You can continue to use getApplicationContext()
, but before use, you should add this flag: dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
, and the error will not show.
Add the following permission to your manifest:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
in Activity just use:
MyActivity.this
in Fragment:
getActivity();
What worked for me was to pass the activity instead of the context.
I wanted a custom layout for my dialog, but to keep my code separate, I created it in a separate Class, else I would have to copy and paste that chunk of code into every activity where I want to use the dialog.
Solution explains my situation but it gives the core solution:
Use the activity[optional name]: Activity[mandatory type] every where until it gets to the dialog you want to inflate
Its a lot of passing around, but it does make more sense over copy and pasting the same code everywhere
Little hack: you can prevent destroying your activity by GC (you should not do it, but it can help in some situations. Don't forget to set contextForDialog
to null
when it's no longer needed):
public class PostActivity extends Activity {
...
private Context contextForDialog = null;
...
public void onCreate(Bundle savedInstanceState) {
...
contextForDialog = this;
}
...
private void showAnimatedDialog() {
mSpinner = new Dialog(contextForDialog);
mSpinner.setContentView(new MySpinner(contextForDialog));
mSpinner.show();
}
...
}
adding
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
and
"android.permission.SYSTEM_ALERT_WINDOW"/>
in manifest
It works for me now. After even close and open the application, gave me the error at that time.
If you are using a fragment and using an AlertDialog / Toast
message, use getActivity()
in the context parameter.
Worked for me.
Cheers!