找出是否填写了数字editText

时间:2015-10-28 15:37:14

标签: android if-statement android-edittext

我有一个名为countOfProduct的 EditText (编号为editText类型,当用户想要插入这个时,只是keyborad显示的数量)和if中我希望看到最终用户插入一个数字或不。 我用谷歌搜索并找到了许多解决方案,但它们都没有为我工作。

这是我的if:

 if(!countOfProduct.getText().toString().equals("") ||
   !countOfProduct.getText().toString().matches("")||
   !countOfProduct.getText().toString().matches(null) ||
   !countOfProduct.getText().toString().equals(null) ||
   !countOfProduct.getText().toString().isEmpty() ||
   !countOfProduct.getText().equals(null) ||
   (countOfProduct.getText().length() ==0) ||
   (countOfProduct.getText().toString().length() ==0))

我该怎么办?

4 个答案:

答案 0 :(得分:2)

我倾向于使用String.isEmpty()来检查:

if(myEditText.getText().toString().isEmpty()) {
   // Bad input
}

它一直对我很好。

修改

注意,TextUtils.isEmpty()可以使用Editable对象(因为此类实现CharSequence),所以如果您愿意,可以使用该方法来避免调用.toString():< / p>

if(TextUtils.isEmpty(myEditText.getText())) {
   // Bad input
}

答案 1 :(得分:0)

尝试:

 String myString = countOfProduct.getText().toString();
 if (!TextUtils.isEmpty(myString)) {
    if (tryParseInt(myString))
        Log.d("IS A NUMBER", "");

 }


 boolean tryParseInt(String value) {  
 try {  
     Integer.parseInt(value);  
     return true;  
  } catch (NumberFormatException e) {  
     return false;  
  }  
 }

答案 2 :(得分:0)

永远记住:EditText.getText()永远不会返回null

如果你不关心空格,这就足够了:

if(countOfProduct.getText().length() != 0){
     // This means that the EditText is not empty
}

如果你关心空格,那就用这个:

if(countOfProduct.getText().toString().trim().length() != 0){
     // This means that the EditText is not empty.
}

答案 3 :(得分:0)

如果您希望用户首先只插入数字,则必须使用 android:inputType 属性将其声明为xml布局:

<EditText
   android:id="@+id/count_of_product"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:inputType="number" >

然后将 TextWatcher 添加到EditText:

countOfProduct.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //insert your checks here
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {
            };
        });

检查this page以了解如何使用 TextWatcher