2014-05-20 28 views
0

這裏是我的第一個問題。 我正在創建一個對話框,以在遊戲菜單中輸入玩家名稱,但想要限制可能的字符(只有字母和數字,如果不可能,至少不包括返回),並防止按下ok按鈕是空的,但我無法弄清楚如何做到這一點。還有一種方法可以將默認操作設置爲恢復正常?我知道很多應用程序都利用它來加快輸入速度。以下是我有:在AlertDialog中需要輸入限制

public String tmPlayerName; 

...

public void playerDialog() { 
    dialogOpen = true; 
    AlertDialog.Builder alert = new AlertDialog.Builder(this); 
    alert.setTitle("Change player"); 
    alert.setMessage("Enter player name (cannot be empty)"); 
    final EditText input = new EditText(this); 
    input.setText(tmPlayerName); 
    input. 
    alert.setView(input); 
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int whichButton) { 
      tmPlayerName = input.getText().toString(); 
      } 
     } 
    }); 
    alert.setNegativeButton("Cancel", 
      new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int whichButton) { 
       } 
      }); 

    alert.show(); 
} 

編輯:應用程序使用的Android 4.0,並使用谷歌播放服務,如果這是任何人的幫助建造。

+0

看到這個答案:http://stackoverflow.com/a/14192231/2649012 –

+0

鏈接中給出的解決方案限制我輸入任何東西。 關於如何限制空提交的任何想法? –

+0

顯示的答案給出了'想限制可能的字符(只有字母和數字')的解決方案,那麼很容易拒絕空文本if(myEdt.getText()。toString.equals(「」)){}' –

回答

0

您可以使用正則表達式來使與文本輸入比較:

String reg = "^[a-zA-Z0-9]*$"; 

final AlertDialog.Builder alert = new AlertDialog.Builder(this); 


      alert.setTitle("Change player"); 
      alert.setMessage("Enter player name (cannot be empty)"); 
      final EditText input = new EditText(this); 

      input.setText("test"); 

      alert.setView(input); 
      alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int whichButton) { 
        String tmPlayerName = input.getText().toString(); 
        if(tmPlayerName.matches(reg)&&!tmPlayerName.isEmpty()){ 
         Log.i("ALERT","Store username -"+tmPlayerName); 
        }else{ 
         Toast.makeText(MainActivity.this, "Please put valid username", Toast.LENGTH_LONG).show(); 
        } 

       } 

      }); 
      alert.setNegativeButton("Cancel", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int whichButton) { 
         } 
       }); 

      alert.create().show(); 

如果你想確定按鈕禁用,而它是空的......我的建議是使用定製對話框。試試這個例子 - http://www.helloandroid.com/tutorials/how-display-custom-dialog-your-android-application

+0

作爲一個非常好的解決方法,但希望它有更多限制,例如,如果文本無效並且只能輸入有效字符,則不能按下OK。出於某種原因,我無法使InputFilter方法正常工作 –

+0

請檢查我的最後一個註釋.. 如果你想讓OK按鈕被禁用,而它是空的...我的建議是使用自定義對話框,試試這個例子 - http://www.helloandroid.com/tutorials/如何-顯示自定義對話框,您-的Android應用程序 –