gpt4 book ai didi

android - 如何在 EditText 中用逗号分隔数字

转载 作者:行者123 更新时间:2023-12-02 14:26:42 26 4
gpt4 key购买 nike

我有一个 EditText,其 inputType 为 number。当用户打字时,我想用逗号分隔数字。这是一个小例子:

123 would be represented as 123

1234 would be represented as 1,234

12345 would be represented as 12,345

...and so on.

我尝试使用 TextWatcher 添加逗号,如下所示:

    EditText edittext = findViewById(R.id.cashGiven);

edittext.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) {

}

@Override
public void afterTextChanged(Editable editable) {
editText.setText(separateWithComma(editText.getText().toString().trim()));
}
});

在此处粘贴 separateWithComma() 方法会使这个问题变得格外冗长,但它确实有效:我在 Eclipse 上测试了它。我认为 addTextChangedListener 不能以这种方式工作,因为当我这样做时,我的应用程序卡住(然后崩溃)。

有没有更好的方法来实现这个目标?感谢您的积极回应。

最佳答案

试试这个代码:

et.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub

}

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

try {
String givenstring = s.toString();
Long longval;
if (givenstring.contains(",")) {
givenstring = givenstring.replaceAll(",", "");
}
longval = Long.parseLong(givenstring);
DecimalFormat formatter = new DecimalFormat("#,###,###");
String formattedString = formatter.format(longval);
et.setText(formattedString);
et.setSelection(et.getText().length());
// to place the cursor at the end of text
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

et.addTextChangedListener(this);

}
});

See this post

关于android - 如何在 EditText 中用逗号分隔数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54728098/

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