【问题标题】:Different behavior with diffrent device in DecimalFormatDecimalFormat 中不同设备的不同行为
【发布时间】:2019-06-22 09:15:08
【问题描述】:

我有一个EditText,可以将用户输入(例如,1000000 转换为 1,000,000)。这是我用作转换器的代码:

private TextWatcher onTextChangedListener(final EditText editText) {
        return 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) {
                editText.removeTextChangedListener(this);

                try {
                    String originalString = s.toString();

                    Long longval;
                    if (originalString.contains(",")) {
                        originalString = originalString.replaceAll(",", "");
                    }
                    longval = Long.parseLong(originalString);

                    DecimalFormat formatter = new DecimalFormat("###,###,###");
                    String formattedString = formatter.format(longval);

                    //setting text after format to EditText
                    editText.setText(formattedString);
                    editText.setSelection(editText.getText().length());
                } catch (NumberFormatException nfe) {
                    nfe.printStackTrace();
                }

                editText.addTextChangedListener(this);
            }
        };
    }

当我在模拟器(API 25 和 29)上尝试它时,它运行正常,我输入的 EditText 格式正确(1,000,000),但是当我发布应用程序时,人们报告格式已变为 1.000000 和然后当使用 EditText 周围的函数时,应用程序崩溃,商店崩溃报告说这是一个 NumberFormatException。什么可能导致此问题,我该如何解决?

【问题讨论】:

  • 可能是arabic 数字。在您对转换器进行任何操作之前,您必须检查 arabic 数字并求解。

标签: android android-edittext decimalformat android-textwatcher


【解决方案1】:

原来是语言环境问题,我在那里使用的代码没有提供语言环境设置,如果另一个设备使用不同的语言环境,则会导致不同的格式。所以我实现了这段代码:

DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH);
DecimalFormat formatter = new DecimalFormat("###,###,###", symbols);

它适用于具有不同语言环境的设备

【讨论】:

    猜你喜欢
    • 2021-01-24
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    相关资源
    最近更新 更多