为edittext设置特定的区域设置

时间:2014-06-09 13:12:27

标签: java android eclipse

我在输入EditText时使用TextWatcher编辑值 这是我的TextWatcher

public class NumberTextWatcher implements TextWatcher {

private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;

private EditText et;

public NumberTextWatcher(EditText et)
{
    df = new DecimalFormat("#,###");

    df.setDecimalSeparatorAlwaysShown(true);
    dfnd = new DecimalFormat("#,###");
    this.et = et;
    hasFractionalPart = false;
}

@SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";

@Override
public void afterTextChanged(Editable s)
{
    et.removeTextChangedListener(this);

    try {
        int inilen, endlen;
        inilen = et.getText().length();

        String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
        Number n = df.parse(v);
        int cp = et.getSelectionStart();
        if (hasFractionalPart) {
            et.setText(df.format(n));
        } else {
            et.setText(dfnd.format(n));
        }
        endlen = et.getText().length();
        int sel = (cp + (endlen - inilen));
        if (sel > 0 && sel <= et.getText().length()) {
            et.setSelection(sel);
        } else {
            // place cursor at the end?
            et.setSelection(et.getText().length() - 1);
        }
    } catch (NumberFormatException nfe) {
        // do nothing?
    } catch (ParseException e) {
        // do nothing?
    }

    et.addTextChangedListener(this);
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
    if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
    {
        hasFractionalPart = true;
    } else {
        hasFractionalPart = false;
    }
}

之后,我尝试使用以下代码将值解析为double:

String amount1 = amount.getText().toString().replaceAll("[^\\d]", "");          
            String duration1 = duration.getText().toString().replaceAll("[^\\d]", "");
            String interest1 = interest.getText().toString().replaceAll("[^\\d]", "");

但问题是,当设备默认语言不是英语时,它可以将字符串解析为双打,所以我认为我为editTexts设置了US Locale!这可能吗?如果没有,我该怎么办才能将值解析成双打?

DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);

1 个答案:

答案 0 :(得分:1)

当你控制后端时,我发现最容易处理你期望的语言并进行了大量的测试。因此,当我在内部的文件上处理文件IO时,在执行任何文件创建代码之前,我总是在注释结束时调用您的调用。在我的情况下,它将是

final DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH); //Format our data to two decimal places for brightness change.
String stringFormat = "#0.00";
decimalFormat.applyPattern(stringFormat);
decimalFormat.format(dataString);

然后,无论设备实际设置为何种语言,您始终都在处理您习惯使用的语言环境。这将有助于处理可能使用不同数字格式的其他语言,例如在这种情况下,因为我正在处理数字。由于您正在处理双打,因此您可能正在接近此数字翻译问题。但是,如果您正在处理来自EditText的输入,那么仅在我的后端的这种特殊方法可能不适用。但我认为沟通我的方法可能仍然有点帮助;希望无论如何。分享并不痛苦。