欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android判断输入是否只包含数字并且执行跳转功能

程序员文章站 2022-03-18 23:45:13
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...
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(); } } } }