Android EditText具有输入类型编号,使文本上的值始终更改>;0

Android EditText具有输入类型编号,使文本上的值始终更改>;0,android,android-edittext,textwatcher,Android,Android Edittext,Textwatcher,我目前正在进行验证,其中我有一个带有inputtype编号的edittext,用于显示在用户购物车中购买的商品数量。我想确保在编辑edittext的值时,如果该值为“、”0”或“00”等,只要该值小于1,则该值将设置为“1” 我已经厌倦了下面的代码: txtJumlah.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged

我目前正在进行验证,其中我有一个带有inputtype编号的edittext,用于显示在用户购物车中购买的商品数量。我想确保在编辑edittext的值时,如果该值为“、”0”或“00”等,只要该值小于1,则该值将设置为“1”

我已经厌倦了下面的代码:

        txtJumlah.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int jumlah = Integer.parseInt(txtJumlah.getText().toString());
                if(txtJumlah.getText().toString().equals("") || jumlah <= 1) {
                    txtJumlah.setText("1");
                }
                calculate();
            }
        });
txtJumlah.addTextChangedListener(新的TextWatcher(){
@凌驾
更改前文本之前的公共void(字符序列s、int start、int count、int after){
}
@凌驾
public void onTextChanged(字符序列、int start、int before、int count){
}
@凌驾
公共无效后文本已更改(可编辑){
int jumlah=Integer.parseInt(txtJumlah.getText().toString());
if(txtJumlah.getText().toString().equals(“”| | jumlah当您将文本设置为“1”时,它将调用PostTextChanged,并一次又一次地导致无限循环。请尝试将jumlah<1改为将jumlah<1放在if语句中。

当您将文本设置为“1”时它将一次又一次地调用afterTextChanged,从而导致无限循环。请尝试将jumlah<1替换为if语句。

替换此:

if(txtJumlah.getText().toString().equals("") || jumlah <= 1) {
     txtJumlah.setText("1");
}
这可能导致
ParseException
(如果
txtJumlah.getText().toString()
是字符串而不是数字)

替换此项:

if(txtJumlah.getText().toString().equals("") || jumlah <= 1) {
     txtJumlah.setText("1");
}
这可能会导致
ParseException
(如果
txtJumlah.getText().toString()
是字符串而不是数字)

txtJumlah.getText()将永远不会返回null。它将始终返回空字符串。唯一可能导致NullPointerException的是TextView为null。即使您尝试设置text(null)它会将其转换为空字符串。txtJumlah.getText()永远不会返回null。它将始终返回空字符串。唯一可能导致NullPointerException的是TextView是否为null。即使您尝试设置Text(null),它也会将其转换为空字符串。
int jumlah = Integer.parseInt(txtJumlah.getText().toString());