更新,想要限制输入类型只需要在xml文件里设置android:inputType=“number”(“decimal”)用以达到限制的目的
private class JumpNextClass implements TextWatcher {
private EditText thisView;
private View nextView;
public String str_before;
public JumpNextClass(EditText vThis, View vNext) {
super();
thisView = vThis;
nextView = vNext;
}
@Override //保存输入新字符前的text,如输入错误可更改
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
str_before = s.toString();
}
//判断是否是数字,如果不是则改为原来的text
public void onTextChanged(CharSequence s, int start, int before, int count) {
String str = s.toString();
if (str.contains("\r") || str.contains("\n") || str.contains(" "))
{
thisView.setText(str_before);
thisView.setSelection(start);
}
try {
if ( str.length() == 0 || str == null ) return;
if(str.charAt(str.length()-1) == 'f' || str.charAt(str.length()-1) == 'd'
|| str.charAt(str.length()-1) == 'D' || str.charAt(str.length()-1) == 'F')
{
thisView.setText(str_before);
thisView.setSelection(start);
str = str.substring(0,str.length()-1);
}
double temp = Double.valueOf(str);
} catch ( Exception e ) {
thisView.setText(str_before);
thisView.setSelection(start); //使光标位置不变,不然setText()会让光标移到text最前
Toast.makeText(MainActivity.this, "You should input num.", Toast.LENGTH_SHORT).show();
}
}
public void afterTextChanged(Editable s) {
if (s.toString().contains("\r") || s.toString().contains("\n")) //如果输入了换行符那么跳转
{
if (nextView != null && nextView instanceof EditText) {
nextView.requestFocus();
EditText temp = (EditText)nextView;
temp.setSelection(temp.getText().length());
} else if ( nextView instanceof Button )
{
Button temp = (Button)nextView;
temp.setFocusable(true);
temp.setFocusableInTouchMode(true);
temp.requestFocus();
}
}
}
}