2013-02-12 58 views
2

我們可以通過添加一個積極的按鈕,實現安卓:警告對話框驗證有道

final EditText urlEditText = new EditText(this); 

DialogInterface.OnClickListener event = new DialogInterface.OnClickListener() { 

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

       try 
       { 
        // Validate URL 
        new URL(urlEditText.getText().toString()); 
        Toast.makeText(getBaseContext(), "URL Accepted", 1).show(); 
       } 
       catch (MalformedURLException e) { 
        Toast.makeText(getBaseContext(), "Invalid URL", 1).show(); 
       } 
      } 
     }; 

AlertDialog dialog = new AlertDialog.Builder(this) 
        .setTitle("Enter the server URL here") 
        .setNegativeButton("Cancel", null) 
        .setPositiveButton("Ok",event) 
        .setView(urlEditText) 
        .create(); 
     dialog.show(); 

如果我們輸入一個錯誤的URL將被驗證,並顯示一個錯誤的URL Toast進行驗證。但是,對話框會被解除,應該一直顯示,直到用戶按下「取消」或輸入正確的URL。這裏有解決方案,像重新創建對話框並再次顯示給用戶,但這是一個好主意。

有沒有辦法,如果我們輸入一個錯誤的URL AlertDialog仍然存在?

回答

8

我們可以使用AlertDialog.getButton(),所以我們可以得到AlertDialog的按鈕引用。如果對話框顯示給用戶,這應該被調用。

final EditText urlEditText = new EditText(this); 


final AlertDialog dialog = new AlertDialog.Builder(this) 
        .setTitle("Enter the server URL here") 
        .setNegativeButton("Cancel", null) 
        .setPositiveButton("Ok",null) 
        .setView(urlEditText) 
        .create(); 
     dialog.setOnShowListener(new OnShowListener() { 

      @Override 
      public void onShow(DialogInterface arg0) { 

       Button okButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); 
       okButton.setOnClickListener(new View.OnClickListener() { 

        @Override 
        public void onClick(View arg0) { 

         try 
         { 
          new URL(urlEditText.getText().toString()); 
          Toast.makeText(getBaseContext(), "URL Accepted", 1).show(); 
          dialog.dismiss(); 
         } 
         catch (MalformedURLException e) { 
          Toast.makeText(getBaseContext(), "Invalid URL", 1).show(); 
         } 
        } 
       }); 
      } 
     }); 

更新1:我們可以用AlertDialog.BUTTON1,但它現在已經過時。

+0

不錯的工作..上帝保佑 – reegan29 2015-06-10 14:25:28

1

URLUtil提供了有用的方法,如

isHttpUrl(); 
isValidUrl(); 

嘗試使用其中一個來驗證EditText中輸入您的網址。並且如果URL無效,請再次顯示警報或不要求dismiss對話框。