You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中如何判断EditText输入值大于500并解决删除时闪退问题

问题原因

你的代码崩溃的核心问题是判断逻辑顺序错误:
你先执行了Long.parseLong()做数值转换,再判断ets2.length()==0的空值场景。当你把输入内容完全清空时,拿到的是空字符串,空字符串无法被转换为Long类型,直接抛出NumberFormatException导致应用崩溃。
此外你的代码还缺少非数字输入的兼容处理,如果用户输入了字母、符号等非数字内容,也会触发相同的崩溃问题。

修正方案

调整判断顺序,先做空值/空串校验,再做数值转换,同时增加异常捕获处理非数字输入场景,修正后代码如下:

ets2.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        // 先取输入内容并去空格
        String inputContent = ets2.getText().toString().trim();
        // 先做空值/空串判断
        if (inputContent.isEmpty()) {
            step2tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            invalidtv.setVisibility(View.VISIBLE);
            ets2.setError("Please enter amount \n greator than 500");
            return;
        }
        // 转换数值加异常捕获,兼容非数字输入场景
        try {
            long inputNum = Long.parseLong(inputContent);
            if (inputNum < 500) {
                step2tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
                invalidtv.setVisibility(View.VISIBLE);
                ets2.setError("Please enter amount \n greator than 500");
            } else {
                step2tv.setCompoundDrawablesWithIntrinsicBounds(0, 0,R.drawable.ic_checkgreen, 0);
                // 符合要求时清除错误提示、隐藏invalidtv
                ets2.setError(null);
                invalidtv.setVisibility(View.GONE);
            }
        } catch (NumberFormatException e) {
            // 输入非数字内容时走错误逻辑
            step2tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            invalidtv.setVisibility(View.VISIBLE);
            ets2.setError("Please enter valid number");
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
});

额外优化说明

原有逻辑中输入符合要求时,没有清除EditText的错误提示,也没有隐藏invalidtv,修正代码里补充了这部分逻辑,同时增加了非数字输入的异常提示,覆盖更多异常输入场景。

内容的提问来源于stack exchange,提问作者Avni Krtigya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 23:15:05