如何检查编辑文本为空

时间:2011-11-01 10:54:45

标签: android android-edittext alertdialog

我正在开发一个应用程序,如果我单击一个按钮,它将检查所有编辑文本是否为空或写入的内容并为该消息提供类似的警告框。我已经制作了一个方法并在Onclick事件中调用它。但我无法得到理想的结果,因为语法错误不是甚至logcat没有显示任何错误,请帮助我...提前谢谢..

    ImageButton b2=(ImageButton)findViewById(R.id.imageButton2);

   b2.setOnClickListener(new OnClickListener()
   {

    @Override
    public void onClick(View arg0) {
        checkValue();

    }

    private void checkValue() {
        EditText e = (EditText) findViewById(R.id.editText1);
           EditText e1 = (EditText) findViewById(R.id.editText2);
           EditText e2 = (EditText) findViewById(R.id.editText3);
           EditText e3 = (EditText) findViewById(R.id.editText4);
           EditText e4 = (EditText) findViewById(R.id.editText5);
           EditText e5 = (EditText) findViewById(R.id.editText6);
        String f = e.getText().toString();
         String f1 = e1.getText().toString(); 
           String f2 = e2.getText().toString();
           String f3 = e3.getText().toString();
           String f4 = e4.getText().toString();
           String f5 = e5.getText().toString();

        if ((f.length()>0)&&(f1.length()>0)&&(f2.length()>0)&&(f3.length()>0)&&(f4.length()>0)&&(f5.length()>0)) { 

            AlertDialog alert= new AlertDialog.Builder(Test.this).create();
            alert.setTitle("Exception:Incomplete Form");
            alert.setMessage("Looks like you missed a field or made a mistake.Please ensure all fields of form are filled.Click OK to go to main page");

            alert.setButton("OK", new DialogInterface.OnClickListener() {

                  public void onClick(DialogInterface dialog, int which) {
                      Intent i=new Intent(Test.this,ShpoonkleActivity.class);

                } }); 

           } 
        else
        {
            AlertDialog alert= new AlertDialog.Builder(Test.this).create();
            alert.setTitle("Your Form is successfully processed.Thanks");
            alert.setMessage("You are Done! Keep an eye out for a confirmation email. If you don't get one in the next 24h, open this form again, and make sure youremail is correct");

        }


    }
    });

}
    }

3 个答案:

答案 0 :(得分:6)

//编辑

我认为你的方法是错误的,你的if语句是在每个填充的时候,当其中一个字段为空时你的其他地方

----上一个答案----

你可以这样做。

if(editText.getText().toString().length() > 0) {
     // editText is not empty
} 

if(editText.getText().toString().length() == 0) {
     // editText is empty
}

答案 1 :(得分:6)

你可以试试这个:

if ((f.trim().equals('') || (f1.trim().equals('') ||........) { 

    // Error , one or more editText are empty

}
else
{
    // all editText are not empty 
}

答案 2 :(得分:6)

Mats和Houcine的答案是有效的,但您甚至可以使用isEmpty()

缩短
if(editText.getText().toString().isEmpty()) {
     // editText is empty
} else {
     // editText is not empty
}