android如果显示对话框

时间:2012-12-13 18:46:09

标签: android alertdialog final

我有摇床和摇动,我想要显示对话。当执行多次抖动时我会遇到问题,因此会显示多个对话框。我希望一次只显示一个对话框。

所以我写了这段代码,但它显示错误。一行想要“最终的AlertDialog”而另一行想要它没有“最终的”

      public void onShake() {

        final AlertDialog builder = null;
         if(!builder.isShowing()){

            builder = new AlertDialog.Builder(getParent()).create(); -- error if final is casted on AlertDialog -- "The final local variable builder cannot be assigned. It must be blank and not using a compound assignment"

            builder.setTitle("Shake");


            builder.setButton("OK", new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int which){
                    builder.dismiss(); -- requires final AlertDialog -- "Cannot refer to a non-final variable builder inside an inner class defined in a different method"

                }
            });
            builder.show();

      }}

编辑:谢谢,dialog.builder();看起来工作。但是现在我遇到了新的问题 - NullPointerException,在线检查是否显示警告对话框。 现在我尝试:

if(builder.isShowing() == false)

修复了NullPointerException

if(builder == null){
builder.setButton("OK", new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int which){
                    dialog.dismiss();
                    builder = null; 
}
}

3 个答案:

答案 0 :(得分:2)

builder.dismiss()更改为dialog.dismiss()

答案 1 :(得分:0)

删除builder.dismiss();并将其替换为dialog.dismis(),在侦听器上会出现一个对话框对象,该对象对应于触发事件的对话框

答案 2 :(得分:0)

将AlertDialog声明为活动中的字段,不需要将其设置为最终字段。