您好,我正在处理一个需求,我有两个编辑文本(文本字段),如果我在第一个文本字段中输入 1,它将递增并在第二个文本字段中显示 2。
我正在获取该功能,但问题是每当我输入一个数字并尝试通过按退格键将其删除时,它就会崩溃。
当第一个文本框中的所有内容都被删除时,我想设置为零。
这是代码。
我的xml代码。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="20dp" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Input Text" />
<EditText
android:id="@+id/myTextBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberSigned" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="After Calculation" />
<EditText
android:id="@+id/outputBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberSigned" />
我的java代码。
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.type2);
final EditText outputTextBox = (EditText) findViewById(R.id.outputBox);
final EditText myTextBox = (EditText) findViewById(R.id.myTextBox);
myTextBox.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
String inputs = myTextBox.getText().toString();
int i = Integer.parseInt(inputs);
i++;
outputTextBox.setText(String.valueOf(i));
}
});
}
最佳答案
您必须检查是否为 null 或空字符串。 try
和 catch
block 有帮助:
try {
String inputs = myTextBox.getText().toString();
int i = Integer.parseInt(inputs);
i++;
outputTextBox.setText(String.valueOf(i));
} catch (NumberFormatException e) {
// Invalid integer received (empty or null string)
outputTextBox.setText("");
}
说明:
如果传递 null 或空字符串,Integer.parseInt
会抛出 NumberFormatException
。如果是这种情况,您只需清除 outputTextBox
。
解决方案2:
按照@rossum的建议手动检查空字符串。
if (TextUtils.isEmpty(inputs)) {
outputTextBox.setText("");
} else {
int i = Integer.parseInt(inputs);
i++;
outputTextBox.setText(String.valueOf(i));
}
关于java - 当我删除Android中的数字时,应用程序崩溃。(文本字段中的内容),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26564302/