如果它是空的,android 中的 EditText.getText() 会返回什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2785907/
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
What does an EditText.getText() in android return if it is empty?
提问by Gaurav Vaish
I've tried null and empty string, any other ideas?
我试过 null 和空字符串,还有其他想法吗?
回答by Gaurav Vaish
No other possibility.
没有其他可能。
getText
, infact, will never return null. It returns CharSequence
whose contents may be empty.
getText
,事实上,永远不会返回空值。它返回CharSequence
其内容可能为空。
Instead of doing getText().toString().equals("")
or vice-versa, it may be faster to do getText().length() == 0
而不是做getText().toString().equals("")
或反之亦然,这样做可能会更快getText().length() == 0
回答by synic
If it's empty, this will work:
如果它是空的,这将起作用:
if(mEditText.getText().toString().equals("")) {
// stuff to run when it's empty
}
Even if it's empty, getText() will still return an Editable, so if you were trying to do this:
即使它是空的,getText() 仍然会返回一个 Editable,所以如果你试图这样做:
if(mEditText.getText().equals("")) {
// stuff
}
It most certainly wasn't working.
它肯定是行不通的。
回答by Karan
You can use TextUtils.isEmpty( mEditText.getText().toString() ). It will return true if its empty/null.
您可以使用 TextUtils.isEmpty( mEditText.getText().toString() )。如果它为空/空,它将返回 true。
回答by Yorma Maassen
The best way I found to check it is to stock the value in a var like:
我发现检查它的最好方法是将值存储在 var 中,例如:
String text = mEditText.getText().toString();
and then to use boolean operator isEmpty
like:
然后使用布尔运算符,isEmpty
如:
if (text.isEmpty){
// stuff
}
回答by Chisko
After looking at several questions and since it's already possible to get a nullI've found the answer to avoid a
在查看了几个问题之后,由于已经有可能获得空值,我找到了避免出现问题的答案
method invocation toString may produce NPE
方法调用 toString 可能会产生 NPE
warning all over the place:
到处警告:
String theText = String.valueOf(mEditText.getText());
String theText = String.valueOf(mEditText.getText());