【问题标题】:Handle Change of TextView according to EditText with Empty value根据具有空值的 EditText 处理 TextView 的更改
【发布时间】:2020-08-19 19:42:26
【问题描述】:

我在名为“deviseValue”的 EditText 上使用TextChangedListener,并对其进行操作以显示sellValue 和buyValue 中的其他值,它们是两个TextViews,如下所示:

deviseValue.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {}
        @Override
        public void afterTextChanged(Editable s) {
            Double dDeviseValue = Double.valueOf(deviseValue.getText().toString());
            Double sellResult = dDeviseValue*dSellValue;
            Double buyResult = dDeviseValue*dBuyValue;
            sellValue.setText(sellResult.toString());
            buyValue.setText(buyResult.toString());
        }
    });

一切正常,但是,当我删除 deviseValue 的所有值(即:EMPTY)时......我的应用程序崩溃了!!

如何处理这种情况,当用户删除所有值时,deviseValue 自动变为 > 1。?

【问题讨论】:

    标签: android textview android-edittext


    【解决方案1】:

    应用程序崩溃,因为您尝试将字符串值从编辑文本转换为双精度值。但是当你清除你的edittext deviseValue.getText().toString() 是“”(空)。这就是你得到 NumberFormatException 的原因。

    在将其转换为双精度之前尝试检查 deviseValue.getText().toString()。 例如:

    String dDeviseText = etEmail.getText().toString();
    Double dDeviseValue = Double.valueOf(dDeviseText.isEmpty() ? "1" : dDeviseText);
    

    并且您应该防止在此编辑文本中输入非数字字符。

    【讨论】:

      猜你喜欢
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多