我正在创建转换器应用程序。我想设置 EditText,以便当用户输入要转换的数字时,千位分隔符( ,
)应该在数字递增 3 位后自动实时添加到数字中:千,百万, 亿等
当擦除到 4 位数以下时,数字恢复正常。
有什么帮助吗?
原文由 Asiimwe 发布,翻译遵循 CC BY-SA 4.0 许可协议
我正在创建转换器应用程序。我想设置 EditText,以便当用户输入要转换的数字时,千位分隔符( ,
)应该在数字递增 3 位后自动实时添加到数字中:千,百万, 亿等
当擦除到 4 位数以下时,数字恢复正常。
有什么帮助吗?
原文由 Asiimwe 发布,翻译遵循 CC BY-SA 4.0 许可协议
即使——虽然已经晚了。供未来的访客使用。
以下代码的特点
将千位分隔符放在 EditText
中,因为它的文本发生变化。
添加 0.
按下句点 (.) 时自动添加。
忽略开头的 0
输入。
只需复制以下名为的类
实现 TextWatcher 的 NumberTextWatcherForThousand
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import java.util.StringTokenizer;
/**
* Created by skb on 12/14/2015.
*/
public class NumberTextWatcherForThousand implements TextWatcher {
EditText editText;
public NumberTextWatcherForThousand(EditText editText) {
this.editText = editText;
}
@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) {
try
{
editText.removeTextChangedListener(this);
String value = editText.getText().toString();
if (value != null && !value.equals(""))
{
if(value.startsWith(".")){
editText.setText("0.");
}
if(value.startsWith("0") && !value.startsWith("0.")){
editText.setText("");
}
String str = editText.getText().toString().replaceAll(",", "");
if (!value.equals(""))
editText.setText(getDecimalFormattedString(str));
editText.setSelection(editText.getText().toString().length());
}
editText.addTextChangedListener(this);
return;
}
catch (Exception ex)
{
ex.printStackTrace();
editText.addTextChangedListener(this);
}
}
public static String getDecimalFormattedString(String value)
{
StringTokenizer lst = new StringTokenizer(value, ".");
String str1 = value;
String str2 = "";
if (lst.countTokens() > 1)
{
str1 = lst.nextToken();
str2 = lst.nextToken();
}
String str3 = "";
int i = 0;
int j = -1 + str1.length();
if (str1.charAt( -1 + str1.length()) == '.')
{
j--;
str3 = ".";
}
for (int k = j;; k--)
{
if (k < 0)
{
if (str2.length() > 0)
str3 = str3 + "." + str2;
return str3;
}
if (i == 3)
{
str3 = "," + str3;
i = 0;
}
str3 = str1.charAt(k) + str3;
i++;
}
}
public static String trimCommaOfString(String string) {
// String returnString;
if(string.contains(",")){
return string.replace(",","");}
else {
return string;
}
}
}
在您的 EditText
上使用此类,如下所示
editText.addTextChangedListener(new NumberTextWatcherForThousand(editText));
将输入作为纯双文本
像这样使用同一个类的 trimCommaOfString
方法
NumberTextWatcherForThousand.trimCommaOfString(editText.getText().toString())
原文由 Shree Krishna 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答798 阅读✓ 已解决
2 回答2.1k 阅读
2 回答929 阅读✓ 已解决
1 回答1.1k 阅读✓ 已解决
1 回答694 阅读✓ 已解决
2 回答791 阅读
2 回答760 阅读
您可以在
String.format()
中使用TextWatcher
。 格式说明符中的逗号可以解决问题。这不适用于浮点输入。并注意不要使用 TextWatcher 设置无限循环。