我必须EditBox
检查用户输入的号码是否正确。为此,我想调用这样一个事件,该事件允许用户在EditBox
数字正确时输入数字,否则,如果数字不正确,则不允许用户输入EditBox
. 怎么做?任何例子都会对我有所帮助。
问问题
2127 次
4 回答
4
在其 beforeTextChangedMethod() 中使用onTextChangedListener()
和验证 .. 像这样的东西..
((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
}
});
于 2012-04-26T06:52:29.290 回答
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
}
});
于 2012-04-26T07:17:57.117 回答
1
您将不得不使用TextWatcher。
你可以去这里。这里也给出了例子,你可以参考一下。
于 2012-04-26T06:56:42.837 回答
0
您可以使用 2 种方式
1. textwatcher
2. Inputfilter
我附上了包含两者的代码
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;
}}
于 2012-04-26T07:18:44.547 回答