如何防止用户输入零作为输入? [英] How to prevent user from entering zero as an input?

查看:62
本文介绍了如何防止用户输入零作为输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将输入验证添加到用户输入数字值的三个EditText集合中. 我面临的问题是计算工作正常,用户无法输入零,因为输入字段之一会导致应用程序崩溃.

I'm trying to add input validation to a set of three EditTexts that the user enter numeric values into. The problem I'm facing is for the calculation to work the user can't enter zero as one of the input fields or the application will crash.

我尝试实现以下内容以防止输入零并显示警告消息.我收到一条错误消息,指出无法启动活动calcResult",它是显示计算的活动.

I tried to implement the following to prevent zero from being entered and show a warning message.I get an error stating that "unable to start activity calcResult" which is the activity that shows the calculation.

这是错误日志的链接: http://pastebin.com/hDsabjR6

This is the link to the error log: http://pastebin.com/hDsabjR6

据此我知道零值仍在通过验证,但是我不知道为什么?

I understand from this that the zero value is still slipping through the validation but I don't know why?

 String getoffsetlength = offsetLength.getText().toString(); 

 if (getoffsetlength.trim().equals('0')) {

     Toast.makeText(this, "Enter number greater than 0!", Toast.LENGTH_SHORT).show();
     return;
   }

当我在应用程序中使用此验证时,应用程序崩溃.关于我在哪里弄乱了此实现的任何想法?

The application crashes when I have used this validation in the app.Any ideas as to where I have messed up with this implementation?

推荐答案

只需将android:digits="123456789"添加到XML的EditText中.这样,用户将无法输入0

Just add android:digits="123456789" to the EditText in XML. This way the user won't be able to input 0

但是,如果要避免用户仅在开头输入0,请使用以下命令:

However, if you want to avoid the user from entering 0 only at the beginning, then use this:

code_text.addTextChangedListener(new TextWatcher(){
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                if (code_text.getText().toString().matches("^0") )
                {
                    // Not allowed
                    Toast.makeText(context, "not allowed", Toast.LENGTH_LONG).show();
                    code_text.setText("");
                }
            }
            @Override
            public void afterTextChanged(Editable arg0) { }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        }); 

这篇关于如何防止用户输入零作为输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆