如何在非activity class android中打开小window
How to open a small window in non activity class in android
我正在尝试找到一种方法来打开一个小 window,它连同非 activity class 中的一个按钮。基本上我尝试使用这种方式:
public class Mytest{
private Context context;
public Mytes(Context context)
{
this.context = context.getApplicationContext();
}
AlertDialog alertDialog = new AlertDialog.Builder(context).create(); //Use context
alertDialog.setTitle("Warning");
alertDialog.setMessage("You are currently in a battle");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
但出现异常
Unable to add window -- token null is not for an application
我看到一个线程,其中有人建议使用 activity 而不是上下文。我尝试了两种方法,从我的主 activity:
将上下文设置为非 activity class
mytest = new Mytest(MainActivity.this);
但它不起作用。任何其他解决方案。
而不是 getApplicationContext(),只需使用 ActivityName.this。
尝试像这样编辑构造函数:
public Mytes(Context context) {
this.context = context;
}
我正在尝试找到一种方法来打开一个小 window,它连同非 activity class 中的一个按钮。基本上我尝试使用这种方式:
public class Mytest{
private Context context;
public Mytes(Context context)
{
this.context = context.getApplicationContext();
}
AlertDialog alertDialog = new AlertDialog.Builder(context).create(); //Use context
alertDialog.setTitle("Warning");
alertDialog.setMessage("You are currently in a battle");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
但出现异常
Unable to add window -- token null is not for an application
我看到一个线程,其中有人建议使用 activity 而不是上下文。我尝试了两种方法,从我的主 activity:
将上下文设置为非 activity classmytest = new Mytest(MainActivity.this);
但它不起作用。任何其他解决方案。
而不是 getApplicationContext(),只需使用 ActivityName.this。
尝试像这样编辑构造函数:
public Mytes(Context context) {
this.context = context;
}