我在公共类中声明AlertBox
方法并在其他类中使用它时遇到以下错误:
“android.view.WindowManager $ BadTokenException:无法添加窗口 - 令牌null不适用于应用程序“
private void AlertBox(String s, final String err, final Context con){
AlertDialog.Builder builder1 = new AlertDialog.Builder(con).create();
builder1.setMessage(s); builder1.setCancelable(true);
builder1.setPositiveButton( "Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}); builder1.show(); }
我查了帖子:
“Single alert dialog for entire application” 但没有一个解决方案适合我。
答案 0 :(得分:0)
你可以试试这个
private void AlertBox(String title, final String err, final Context con){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(con);
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(err);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
Toast.makeText(con, "You clicked on YES", Toast.LENGTH_SHORT).show();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(con, "You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
导入此import android.support.v7.app.AlertDialog;