这是删除按钮监听代码:
//del 按钮的监听
btnDel = (Button) findViewById(R.id.delete);
btnDel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
btnDel.setOnClickListener(this);//短按
//btnDel.setOnLongClickListener(this);//长按
editText.setText(editText.getText().toString().substring(0, editText.getText().toString().length()-1)); //sub -1
}
});
这是logcat:
03-09 16:18:52.603: D/android.widget.GridLayout(2490): horizontal constraints: x4-x0>=768, x4-x3<=128, x3-x2<=128, x2-x1<=128, x1-x0<=128 are inconsistent; permanently removing: x4-x3<=128.
03-09 16:18:52.917: D/gralloc_ranchu(2490): Emulator without host-side GPU emulation detected.
03-09 16:18:53.622: I/Choreographer(2490): Skipped 40 frames! The application may be doing too much work on its main thread.
03-09 16:19:02.465: D/AndroidRuntime(2490): Shutting down VM
03-09 16:19:02.465: E/AndroidRuntime(2490): FATAL EXCEPTION: main
03-09 16:19:02.465: E/AndroidRuntime(2490): Process: com.example.calculatedemo, PID: 2490
03-09 16:19:02.465: E/AndroidRuntime(2490): java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=-1
03-09 16:19:02.465: E/AndroidRuntime(2490): at java.lang.String.startEndAndLength(String.java:298)
03-09 16:19:02.465: E/AndroidRuntime(2490): at java.lang.String.substring(String.java:1087)
03-09 16:19:02.465: E/AndroidRuntime(2490): at com.example.calculatedemo.MainActivity$2.onClick(MainActivity.java:85)
03-09 16:19:02.465: E/AndroidRuntime(2490): at android.view.View.performClick(View.java:5198)
03-09 16:19:02.465: E/AndroidRuntime(2490): at android.view.View$PerformClick.run(View.java:21147)
03-09 16:19:02.465: E/AndroidRuntime(2490): at android.os.Handler.handleCallback(Handler.java:739)
03-09 16:19:02.465: E/AndroidRuntime(2490): at android.os.Handler.dispatchMessage(Handler.java:95)
03-09 16:19:02.465: E/AndroidRuntime(2490): at android.os.Looper.loop(Looper.java:148)
03-09 16:19:02.465: E/AndroidRuntime(2490): at android.app.ActivityThread.main(ActivityThread.java:5417)
03-09 16:19:02.465: E/AndroidRuntime(2490): at java.lang.reflect.Method.invoke(Native Method)
03-09 16:19:02.465: E/AndroidRuntime(2490): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-09 16:19:02.465: E/AndroidRuntime(2490): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
The reason has been found. When the length of the edit box is 0, an error will be reported when deleting it. Just judge the length of the edit box: