App*_*rew 56 android android-edittext
在网上我看到的例子如edittext.getText().toString().我没有看到任何空检查.在文档中,我没有看到任何声明,它永远不会为空.
不过,观察结果表明了什么; 这是否会返回null?
sti*_*ike 65
getText()不会回来null.因此NPE在以下方法中没有机会.在getText将返回空字符串,如果没有字符串,它绝对不是null
getText().toString();
Run Code Online (Sandbox Code Playgroud)
但是,null如果没有正确初始化edittext本身,因此以下内容将触发NPE
editText.getText().toString();
Run Code Online (Sandbox Code Playgroud)
Ada*_*hns 27
更新:
老答案:
不,EditText.getText()永远不会回来null.验证这一点的一种方法是检查Android源代码EditText.getText():
public Editable getText() {
return (Editable) super.getText();
}
Run Code Online (Sandbox Code Playgroud)
因为EditText extends TextView,super.getText()必须要来电TextView.getText().现在我们继续TextView.getText()看看它返回的内容:
public CharSequence getText() {
return mText;
}
Run Code Online (Sandbox Code Playgroud)
现在我们需要知道是否mText可能为空.
深入研究TextView.java源代码,我们看到它mText在TextView构造函数中初始化为空字符串:
public TextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mText = "";
…
}
Run Code Online (Sandbox Code Playgroud)
一旦我们看到EditText构造函数调用TextView构造函数:
public EditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
Run Code Online (Sandbox Code Playgroud)
我们可以安全地得出结论,EditText.getText()它永远不会返回null,因为只要EditText构造一个,mText就会得到一个空字符串的值.
但是,正如StinePike指出的那样,EditText.getText()如果您的EditText是null在调用时,可能会导致NPE getText().
使用Android P SDK,它在AppCompatEditText类中被注释为可为空,因此它可以返回空值。
从文档中:
返回视图显示的文本。如果尚未设置可编辑文本,则返回 null。
@Override
@Nullable
public Editable getText() {
if (Build.VERSION.SDK_INT >= 28) {
return super.getText();
}
// A bug pre-P makes getText() crash if called before the first setText due to a cast, so
// retrieve the editable text.
return super.getEditableText();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26566 次 |
| 最近记录: |