我有EditBox
我必须检查用户输入的号码是否正确。为此,我想调用这样一个事件,允许用户在数字正确时键入EditBox
中的数字,否则如果数字不正确,则不允许用户输入在编辑框中。如何做到这一点。任何例子对我都有帮助。
答案 0 :(得分:4)
使用onTextChangedListener()
并在其beforeTextChangedMethod()中进行验证..这样的事情..
((EditText)findViewById(R.id.et_testo)).addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
((TextView)findViewById(R.id.numcaratteri)).setText(String.format(getString(R.string.caratteri), s.length()));
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// Validate here
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
});
答案 1 :(得分:2)
final Pattern pattern = Pattern.compile("[0-9]");
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
Matcher matcher = pattern.matcher(s);
if (matcher.find())
{
s.replace(0, s.length(), s.toString().replaceAll("[0-9]", ""));
}
}
public void beforeTextChanged(CharSequence s, int start,
int before, int count) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
});
答案 2 :(得分:1)
您必须使用TextWatcher。
你可以去HERE。这里也给出了示例,您可以参考它。
答案 3 :(得分:0)
你可以使用2种方式
textwatcher
2.输入过滤器
我附上包含两者的代码
public class MainActivity extends Activity {
EditText editTxt;
private TextView regresult;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTxt =(EditText)findViewById(R.id.editID);
regresult = (TextView)findViewById(R.id.txtID);
String urName=editTxt.getText().toString();
editTxt.setFilters(new InputFilter[]{new DecimalDigitsInputFilter()});
editTxt.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
@Override
public void afterTextChanged(Editable s) {
if (editTxt.getText().toString().matches("(^([0-9]{0,3})?)(\\.[0-9]{0,1})?$"))
{
regresult.setText("");
}
else
{
regresult.setText("invalid number");
}
}
});
}}
class DecimalDigitsInputFilter implements InputFilter
{
Pattern mPattern;
public DecimalDigitsInputFilter()
{
mPattern = Pattern.compile("(^([0-9]{0,2})?)(\\.[0-9]{0,1})?$"); //here u can give your required pattern
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// TODO Auto-generated method stub
Matcher matcher = mPattern.matcher(dest);
if(!matcher.matches())
{
return "";
}
return null;
}}