2017-12-27 181 views
0

我正在使用以下代码来显示AlertDialog并提示用户按“重试”。对话框应保持在屏幕上,直到连接可用。该应用程序工作正常,当网络不可用时,该对话框出现。如何在网络不可用时在屏幕上保留AlertDialog

问题是,只要我触摸屏幕上某处或按下重试,对话框就会被解除!我怎样才能防止呢?

+0

使用这种LIB编译 'com.github.nikhilborad:basehelp:1.02' 有法nbShowNoInternet()..多数民众赞成。 –

回答

1

您可以使用setCanceledOnTouchOutside(false)

AlertDialog mDialog = builder.create(); 
    mDialog.setCanceledOnTouchOutside(false); 
     mDialog.show(); 

但是,这将防止只有外部触摸不正面或负面按钮点击。其AlertDialog的默认行为是关闭任何按钮上的对话框,不管您是否拨打dismiss()。所以,如果你想要超越这种行为,你可以做这样的事情。

AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    builder.setTitle("Not Connected") 
      .setIcon(R.drawable.ic_play_icon) 
      .setView(R.layout.item_dialog) 
      .setCancelable(false) 
      .setMessage("You are not connected to the Internet"); 
    final AlertDialog mDialog = builder.create(); 
    mDialog.setCanceledOnTouchOutside(false); 
    mDialog.setOnShowListener(new DialogInterface.OnShowListener() { 

     @Override 
     public void onShow(DialogInterface dialogInterface) { 
      Button button = mDialog.getButton(AlertDialog.BUTTON_POSITIVE); 
      button.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        //Do your validations task here 

       } 
      }); 
     } 
    }); 
    mDialog.show(); 
1

setCancelable(false)将为您工作。

AlertDialog.Builder builder = new AlertDialog.Builder(MainGroupActivity.this); 
    builder.setTitle("Not Connected") 
      .setIcon(R.drawable.disconnect) 
      .setView(mProgressBar) 
      .setCancelable(false) 
      .setMessage("You are not connected to the Internet") 
      .setPositiveButton("Retry", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialogInterface, int i) { 
        //Retry connection 
        if(isNetworkAvailable()) 
         mDialog.dismiss(); 
       } 
      }); 
+0

setCancelable(false)方法不起作用 – JasonStack

0

您的alertDialog建设添加setCancelable(false)

mProgressBar = new ProgressBar(MainGroupActivity.this); 
     AlertDialog.Builder builder = new AlertDialog.Builder(MainGroupActivity.this); 
     builder.setTitle("Not Connected") 
       .setIcon(R.drawable.disconnect) 
       .setView(mProgressBar) 
       .setMessage("You are not connected to the Internet") 
       .setCancelable(false) 
       .setPositiveButton("Retry", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialogInterface, int i) { 
         //Retry connection 
         if(isNetworkAvailable()) 
          mDialog.dismiss(); 
        } 
       }); 
     mDialog = builder.create(); 
     if(!isNetworkAvailable()) 
      mDialog.show(); 
相关问题