检查空的edittext android

时间:2014-05-08 00:35:10

标签: android

我有一个edittext,输入类型设置为number。我想检查edittext是否为空。

 <EditText
   android:id="@+id/noOfTranset"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:layout_marginTop="55dp"
   android:layout_marginLeft="20dp"
   android:layout_marginRight="20dp"
   android:hint="Enter number:"
   android:inputType="number"
   android:textColor="@android:color/black"
   android:maxLength="2"/>

下面是我尝试过的代码,但没有检查空的edittext。我在这里错过了什么?感谢。

String numTrans = et1.getText().toString();
int transaction = Integer.parseInt(numTrans);



if(numTrans.trim().length() == 0 || numTrans.equals("") || numTrans == null){

// none of the above conditions check for empty edittext

}

3 个答案:

答案 0 :(得分:1)

问题是您尝试将empty string转换为Integer。当输入文字为Integer.parseIntNumberFormatException时,null会抛出empty

仅在输入文本不为空时将代码更改为解析string to integer

if(!TextUtils.isEmpty(numTrans)){
      int transaction = Integer.parseInt(numTrans);
      // do your other stuff here
 }

答案 1 :(得分:0)

这样的事情怎么样?

EditText usernameEditText = (EditText) findViewById(R.id.editUsername);
sUsername = usernameEditText.getText().toString();
if (sUsername.matches("")) {
    Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
    return;
} 

取自:Check if EditText is empty.

答案 2 :(得分:0)

这很简单,你应该使用trim function来检查:

String numTrans = et1.getText().toString();

if(!numTrans.trim().length() > 0)
{
    int transaction = Integer.parseInt(numTrans);   
    //code here for empty edittext....

}