gpt4 book ai didi

java - InputFilter 内的 IndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-12-01 12:24:54 25 4
gpt4 key购买 nike

在某些 Android 设备上,我在 InputFilter 内遇到了 IndexOutOfBoundsException,我用它来删除输入开头的任何零:

我的代码:

    zeroFilter = new InputFilter()
{
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
{
if(dest.length() == 0)
{
if (source.charAt(0) == '0')
{
return "";
}
}
return null;
}
};

etxtNumbers.setFilters(new InputFilter[]{zeroFilter, new InputFilter.LengthFilter(5)});

堆栈跟踪:

java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
at android.text.SpannableStringBuilder.charAt(SpannableStringBuilder.java:111)
at com.nasseralsalmi.wheel.AddPrivatePlateActivity$1.filter(AddPrivatePlateActivity.java:57)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:428)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:420)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:29)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:667)
at android.view.inputmethod.BaseInputConnection.setComposingText(BaseInputConnection.java:425)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:333)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
at dalvik.system.NativeStart.main(Native Method)

最佳答案

在访问源中的任何字符之前,您必须检查源不为空。

if (source.length() > 0 && source.charAt(0) == '0')
{
return "";
}

关于java - InputFilter 内的 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26441616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com