我有以下代码,我想用它来确保我的edittext不会为空。因此,如果第一个绘制的0(零)被移除,它必须在焦点改变时恢复为0,到目前为止这是应用程序:
package your.test.two;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class TesttwoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText edtxt = (EditText)findViewById(R.id.editText1);
// if I don't add the following the app crashes (obviously):
edtxt.setText("0");
edtxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
update();
}
});
}
public void update() {
EditText edittxt = (EditText)findViewById(R.id.editText1);
Integer i = Integer.parseInt(edittxt.getText().toString());
// If i is an empty value, app crashes so if I erase the zero
//on the phone and change focus, the app crashes
}
}
我在update()方法中尝试了以下内容:
String str = edittxt.getText().toString();
if (str == "") {
edittxt.setText("0");
}
但它不起作用。如何允许edittext永远不会是emty,在空时恢复为零,但在值存在时则不会。我已经确定edittext只能允许数值。
答案 0 :(得分:5)
if(str.equals("")){
edittxt.setText("0");
}
WarrenFaith是对的。请参阅此帖子以了解有关此问题的更多信息:Java String.equals versus ==
答案 1 :(得分:0)
我建议使用try / catch块来覆盖你的parseInt
调用,该块捕获NumberFormatException,这可能是抛出的错误(因为你没有指定,我只能猜测),所以它看起来像:
public void update() {
EditText edittxt = (EditText)findViewById(R.id.editText1);
Integer i;
try {
i = Integer.parseInt(edittxt.getText().toString());
// do something with i
} catch (NumberFormatException e) {
// log and do something else like notify the user or set i to a default value
}
}