Java (Android) 检查 EditText 是否为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24391809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:56:16  来源:igfitidea点击:

(Android) Check if EditText is empty?

javaandroid

提问by Kyle Horkley

How do you check if an EditTextis empty? I want to make it so that if the EditTextis blank, a TextViewvalue will be " " (space). If it's not, resume as normal. How do I go about doing this? Thanks for the help!

你如何检查一个EditText是否为空?我想让它EditText是空白的,一个TextView值将是“”(空格)。如果不是,请照常恢复。我该怎么做?谢谢您的帮助!

采纳答案by Giru Bhai

to check Edittext as empty ,where myeditTextis your edittext

检查 Edittext 为空,myeditText你的 edittext在哪里

if(myeditText.getText().toString().trim().length() == 0)

Or use below function

或使用以下功能

   private boolean isEmpty(EditText myeditText) {
            return myeditText.getText().toString().trim().length() == 0;
        }

If function return falsemeans edittext is not empty and return truemeans edittext is empty

如果函数返回false表示edittext不为空,返回true表示edittext为空

For more info see this best link Check if EditText is empty.

有关更多信息,请参阅此最佳链接检查 EditText 是否为空。

回答by Bartosz Mikulski

EditTexthas a method getText()which returns an instance of Editableand the Editableclass has a method: length(). If the lenght is not 0, your EditTextis not empty.

EditText有一个方法getText(),它返回的实例Editable和所述Editable类有一个方法:length()。如果长度不为 0,则您EditText的不为空。

回答by khurram

String text=yourEditText.getText().toString().trim();
if(text.equal("") || text==null) {
    //Do Somthing...
} 
else {
    //Do something else
}

Good luck

祝你好运

回答by Kanak Sony

If you go through EditTextAPI reference, getText()will return the text as Editable. You can use it like

如果您通过EditTextAPI 参考,getText()将返回文本为Editable. 你可以像这样使用它

if(!TextUtils.isEmpty(myeditText.getText().toString().trim()) {
// Non-empty 
}

回答by ingyesid

you can use this method from android framework

你可以在android框架中使用这个方法

public static boolean isEmpty (CharSequence str)
Added in API level 1

Returns true if the string is null or 0-length.
Parameters
str     the string to be examined
Returns

    true if str is null or zero length 

http://developer.android.com/reference/android/text/TextUtils.html#isEmpty%28java.lang.CharSequence%29

http://developer.android.com/reference/android/text/TextUtils.html#isEmpty%28java.lang.CharSequence%29