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

博客探讨了如何在Android中限制输入框只接受数字,并介绍了通过设置android:inputType属性实现这一功能的方法。
摘要由CSDN通过智能技术生成

更新,想要限制输入类型只需要在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();
            }
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值