2017-07-31 59 views
0

我是一個初學者,開始設計一個簡單的應用程序來跟蹤高爾夫分數。我花了一些時間試圖找出如何向用戶提供通知,他們無法在分數文本框下輸入字母。我曾嘗試使用包含整個字母表的數組,但尚未能使其工作。我目前正在嘗試使用InputFilter,但我沒有取得任何成功;應用程序在輸入信件時會崩潰。如何在EditText中輸入字母時的敬酒

EditText input1 = (EditText)findViewById(R.id.scorePrompt); 
    TextView output1 = (TextView)findViewById(R.id.textTotal); 
    String blankCheck = input1.getText().toString(); //CHANGE INPUT IN scorePrompt TO STRING 

    InputFilter filter = new InputFilter() { 
     public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 
      for (int i = start; i < end; i++) { 
       if (Character.isLetter(source.charAt(i))) { // Accept only letter & digits ; otherwise just return 
        Toast.makeText(getApplicationContext(),"NO LETTERS",Toast.LENGTH_SHORT).show(); 
        return ""; 
       } 
      } 
      return null; 
     } 
    }; 

我懷疑這是因爲我沒有直接將Inputfilter連接到我的blankCheck,但我不確定。任何幫助表示讚賞!

+0

看到https://stackoverflow.com/questions/8543449/how-to-use-the-textwatcher-class-in-android – TWL

+0

請解釋你想要什麼? –

+1

[可惜MyApp已停止。我怎樣才能解決這個問題?](https://stackoverflow.com/questions/23353173/uncomfort-myapp-has-stopped-how-can-i-solve-this) –

回答

0

通常,您要找的答案是源於其他地方的問題的結果。

如果您希望用戶輸入數字而不是文本,最好的解決方案是在他們輸入的EditText字段中指定一個輸入類型的「數字」。這將限制鍵盤輸入只允許數字。

<EditText 
    android:inputType="number" 
    .... other attributes 
</EditText> 
+0

謝謝你的回覆!我有點困惑,我應該如何實現這個到我的代碼。我的計劃是最終在此活動中添加更多功能,這也需要輸入文字,因此我不想完全防止字母輸入。我目前有一個'if'語句來檢查我的EditText中的空白輸入,而對於其他所有情況我都有一個'else'。我能否將你的代碼塊添加到這個'else'方法中? –

+0

不,@RaymondNguyen,我的建議會將鍵盤從一個字母/數字鍵盤更改爲一個10鍵,並且不允許字母字符。這聽起來像我的建議不符合你的想法。 – themichaelscott

0

U可以使用正則表達式的這一點,請看下面的代碼:

//定義要如下使用模式。 //我只支持以下內容:

Pattern keyPattern = Pattern.compile("[0-9a-zA-Z,._]+"); 

yourEditText.addTextChangedListener(new TextWatcher() { 
    @Override 
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 

    @Override 
    public void onTextChanged(CharSequence s, int start, int before, int count) {} 

    @Override 
    public void afterTextChanged(Editable s) { 
    if (!keyPattern .matcher(yourEditText.getText()).matches()) { 
     Toast.makeText(getApplicationContext(),"Your Message",Toast.LENGTH_SHORT).show(); 
        return ""; 
} 
}); 

希望這有助於!