我想完成同样的任务有很多答案,甚至在我的案例中找不到任何有用的解决方案
我见过
Question 1 - 问题在于添加逗号计数“。” (DOT)也作为数值。
Question 2 - 问题是在文本发生变化时没有显示结果
Question 3 - 问题是它在第15个字母后连续添加0。
还有更多问题和答案,
但是我找不到满足千分离器一般要求的任何东西。
是否有任何有用的提示可以帮助我在文本更改时顺利添加千位分隔符并对其进行不同的处理 小数点后的数字如计算器?
我会感激任何帮助。
答案 0 :(得分:12)
我遇到了同样的问题,并为此任务进行了大量研究以获得正确的结果。所以我终于解决了我们正在搜索的问题,并且我正在为您提供我的代码,这些代码将帮助您过多并满足您的要求。
您可以直接在自己的课程中复制我的代码,经过全面测试
以下代码的确认
在EditText
内将千位分隔符作为文本更改。
在按下句点(。)时自动添加0.在第一个。
在Beginning忽略0输入。
班级名称:NumberTextWatcherForThousand
实施TextWatcher
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import java.util.StringTokenizer;
/**
* Created by Shreekrishna on 12/14/2014.
*/
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));
将输入作为纯文本输入Double
使用同一类的trimCommaOfString
方法
NumberTextWatcherForThousand.trimCommaOfString(editText.getText().toString());