我对editText中的限制号有疑问。我想用户只能写1-30的号码。当用户想要放32时我想阻止这种可能性。我想检查一下用户是否先输入第一个数字4我会阻止输入更多数字。当第一个数字3时,我想阻止除0以外的所有nubmers。我该怎么做?我使用textWatcher来观看文字,但是如何阻止键盘?
答案 0 :(得分:1)
试试这种方式
InputFilter filter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
int num = 0;
try {
num = Integer.parseInt(dest.toString()+source.toString());
if (!(num > 0 && num <= 30)) {
return "";
}
} catch (Exception e) {
return "";
}
return null;
}
};
editListenPort.setFilters(new InputFilter[]{filter});
答案 1 :(得分:0)
我做了同样的事情:
editListenPort.addTextChangedListener(new TextWatcher(){
/** Not implemented */
@Override
public void afterTextChanged(Editable arg0) { }
/** Not implemented */
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
/** After text has been entered into the EditText, this updates the TextView
* next to it with the new value. A sanity check is performed if there is no
* text entered at all, upon which the listen port is set to 0. */
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int numberOfChars = s.length();
if(numberOfChars > 0){
mOwnPort = Integer.parseInt(s.toString());
} else if(numberOfChars <= 0){
mOwnPort = 0;
}
((TextView) findViewById(R.id.labelOwnIpData)).setText("Own IP-endpoint:\n" + mOwnIp + ":" + mOwnPort);
}
});
使用这段代码,我检查EditText的输入并更新直接位于EditText旁边的TextView。
虽然如果你更新EditText本身或发出警告,我认为这不是问题。