-1

我有振动器,并且在摇动时我想显示对话。当执行多次摇动时我遇到问题,因此会显示多个对话框。我想一次只显示一个对话框。

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

      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; 
}
}
4

3 回答 3

2

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

于 2012-12-13T18:48:03.960 回答
0

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

于 2012-12-13T18:48:41.467 回答
0

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

于 2012-12-13T18:49:22.770 回答