2014-05-20 71 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应用程序 –