使用Oreo上的EditText单击FAB时的IndexOutOfBoundsException

时间:2018-05-28 14:39:16

标签: java android indexoutofboundsexception

当用户单击FAB以添加计时器或单击TimerEditActivity上的数字按钮时,会出现“java.lang.IndexOutOfBoundsException”错误。这仅在Android 8.0上发生。我尝试了不同的方法,但不知道如何解决这个问题。

void onClick(TextView view) {
        if (mFocusGrabber.isFocused())
            return;
        EditText field = getFocusedField();
        int at = field.getSelectionStart();
        field.getText().replace(at, at + 1, view.getText()); //LINE 116, causing the error
        field.setSelection(at + 1);
//        updateStartButtonVisibility();
        if (field.getSelectionStart() == FIELD_LENGTH) {
            // At the end of the current field, so try to focus to the next field.
            // The search will return null if no view can be focused next.
            View next = field.focusSearch(View.FOCUS_RIGHT);
            if (next != null) {
                next.requestFocus();
                if (next instanceof EditText) {
                    // Should always start off at the beginning of the field
                    ((EditText) next).setSelection(0);
                }
            }
        }
    }

这是Play Console的堆栈跟踪。第116行似乎是罪魁祸首。

    at android.text.SpannableStringBuilder.checkRange (SpannableStringBuilder.java:1309)
      at android.text.SpannableStringBuilder.replace (SpannableStringBuilder.java:510)
      at android.text.SpannableStringBuilder.replace (SpannableStringBuilder.java:504)

      at android.text.SpannableStringBuilder.replace (SpannableStringBuilder.java:502)
      at be.demillennial.oneclock.timers.EditTimerActivity.onClick (EditTimerActivity.java:116)

      at be.demillennial.oneclock.timers.EditTimerActivity$$ViewBinder$7.doClick (EditTimerActivity$$ViewBinder.java:92)
      at butterknife.internal.DebouncingOnClickListener.onClick (DebouncingOnClickListener.java:22)
      at android.view.View.performClick (View.java:6891)
      at android.widget.TextView.performClick (TextView.java:12651)
      at android.view.View$PerformClick.run (View.java:26083)
      at android.os.Handler.handleCallback (Handler.java:789)
      at android.os.Handler.dispatchMessage (Handler.java:98)
      at android.os.Looper.loop (Looper.java:164)
      at android.app.ActivityThread.main (ActivityThread.java:6938)
      at java.lang.reflect.Method.invoke (Native Method)
      at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:327)
      at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1374)

1 个答案:

答案 0 :(得分:1)

如果您的选择在最后

,此行必然会崩溃
field.getText().replace(at, at + 1, view.getText());

如果编辑文本中有6个字符,则无法替换6-7之间的值。它将始终通过IndexOutOfBoundsException

像下一行一样检查一下,它不会崩溃

if (field.getSelectionStart() <= FIELD_LENGTH) {