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
(Android) Check if EditText is empty?
提问by Kyle Horkley
How do you check if an EditText
is empty? I want to make it so that if the EditText
is blank, a TextView
value 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 myeditText
is 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 false
means edittext is not empty and return true
means edittext is empty
如果函数返回false
表示edittext不为空,返回true
表示edittext为空
For more info see this best link Check if EditText is empty.
有关更多信息,请参阅此最佳链接检查 EditText 是否为空。
回答by Bartosz Mikulski
EditText
has a method getText()
which returns an instance of Editable
and the Editable
class has a method: length()
. If the lenght is not 0, your EditText
is 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 EditText
API reference, getText()
will return the text as Editable
. You can use it like
如果您通过EditText
API 参考,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