AlertDialog按钮需要双击

问题描述:

我正在显示用于在我的应用程序中下载文件的进度对话框,但如果用户需要取消下载,那么他将不得不按下后退按钮,然后弹出警报有两个按钮的对话框。问题是我必须双击警报对话框的按钮,然后只有警报对话框被取消。为我提出任何解决方案。AlertDialog按钮需要双击

这里是供您参考代码和平..

@Override 
    protected Dialog onCreateDialog(int id) 
    { 
     switch (id) 
     { 
     case progress_bar_type: 
      pDialog = new ProgressDialog(this); 
      pDialog.setMessage("Downloading file. Please wait..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setMax(100); 
      pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
      pDialog.setOnKeyListener(new DialogInterface.OnKeyListener() { 

       @Override 
       public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { 
        // TODO Auto-generated method stub 
        if(keyCode == KeyEvent.KEYCODE_BACK){ 

         running = false; 
         /*Intent intent = new Intent(context, NewDialog.class); 
         startActivity(intent);*/ 
         AlertDialog.Builder alertDialog = new AlertDialog.Builder(context); 
         alertDialog.setIcon(R.drawable.ic_launcher); 
         alertDialog.setTitle("Ariisto"); 
         alertDialog.setMessage("Do you Want to Cancel the Download ?"); 
         alertDialog.setCancelable(true); 
         alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() { 

          @Override 
          public void onClick(DialogInterface dialog, int which) { 

           File externalFile = new File(Environment.getExternalStorageDirectory(),"downloadedfile.pdf"); 
           externalFile.delete(); 
           pDialog.dismiss(); 
           running = false; 
           Log.d("External File", "DELETED"); 
           pDialog.setProgress(0); 
           count = 2; 
          } 
         }); 
         alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() { 

          @Override 
          public void onClick(DialogInterface dialog, int which) { 
           // TODO Auto-generated method stub 
           new DownloadFileFromURL().execute(file_url); 
           running = true; 
           count = 0; 
          } 
         }); 
         AlertDialog alert = alertDialog.create(); 
         alert.show(); 
        } 
        return false; 
       } 
      }); 

问题是压倒一切onKey()注册您Activity两个事件,KEY_DOWNKEY_UP给定键。所以恰巧你在这两次事件中两次触发了AlertDialog。我建议你重写onKeyDown()方法并将代码移到那里。希望这可以帮助。

+0

嗨Egor ..谢谢你的建议,但是我不能重写onKeyDown(),因为它只显示onKey()在setOnKeyListener中。你能告诉我片段代码onKeyDown()上面的片段..否则重定向我任何好的教程或任何可能有用的链接。谢谢。 –

+0

我也尝试重写onKeyDown()方法的活动,但仍然给它相同的结果。 –

+0

@NitinBathija,是的,我的意思是活动的onKeyDown()方法。 – Egor