我想覆盖EditText的getText()
。
我收到这种字符串:"12,345,678"
我的目的是删除逗号并返回可编辑但是当我的代码出现时我得到一个错误。
public class AmountEditText extends EditText {
@Override
public Editable getText() {
Editable s = super.getText();
if(s!=null && s.length()>0) {
if (s.toString().contains(",")) {
return new SpannableStringBuilder(s.toString().replace(",", ""));
}
}
return s;
}
private TextWatcher watcher = 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) {
int position = getSelectionStart();
int nbCommaBefore;
int nbCommaAfter;
String str = s.toString();
String finalStr;
String formattedStr;
nbCommaBefore = str.length() - str.replace(",", "").length();
boolean containsDot = false;
if (str.contains(".")) {
containsDot = true;
formattedStr = str.split("\\.")[0];
} else {
formattedStr = str;
}
if (!s.toString().isEmpty()) {
removeTextChangedListener(watcher);
formattedStr = formattedStr.replace(",", "");
formattedStr = formattedStr.replaceAll("(\\d)(?=(\\d{3})+$)", "$1,");
if (containsDot) {
if (str.split("\\.").length != 1) {
finalStr = formattedStr + "." + str.split("\\.")[1].replace(",", "");
} else {
finalStr = formattedStr + ".";
}
} else {
finalStr = formattedStr;
}
nbCommaAfter = finalStr.length() - finalStr.replace(",", "").length();
setText(finalStr);
if (position == str.length()){
setSelection(finalStr.length());
}
else if (position == 0)
{
setSelection(0);
}
else if (nbCommaBefore < nbCommaAfter){
setSelection(position + 1);
}
else if (nbCommaAfter < nbCommaBefore){
setSelection(position - 1);
}
else{
setSelection(position);
}
addTextChangedListener(watcher);
}
}
@Override
public void afterTextChanged(Editable s) {
}
};
public AmountEditText(Context context) {
this(context, null);
}
public AmountEditText(Context context, AttributeSet attrs) {
super(context, attrs);
addTextChangedListener(watcher);
}
public AmountEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
addTextChangedListener(watcher);
}
}
E / MessageQueue-JNI:MessageQueue回调中的异常:handleReceiveCallback E / MessageQueue-JNI:java.lang.IndexOutOfBoundsException:setSpan(0 ... 5)在android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1265)结束超过长度4 )在android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:684)的android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:677)在android.widget.SpellChecker $ SpellParser.setRangeSpan(SpellChecker.java:532)在android上.widget.SpellChecker $ SpellParser.parse(SpellChecker.java:515)位于android.widget的android.widget.Editor.updateSpellCheckSpans(Editor.java:679)的android.widget.SpellChecker.spellCheck(SpellChecker.java:242)。 Editor.sendOnTextChanged(Editor.java:1249)位于android.widget.TextView.TextView.setText(TextView.java:4483)android.widget.TextView.TextView.setText(TextView)的android.widget.TextView.sendOnTextChanged(TextView.java:8191) .java:4337)在android.wi上的android.widget.EditText.setText(EditText.java:89) dget.TextView.setText(TextView.java:4312)at org.newtonproject.newpay.widgetlib.AmountEditText $ 1.onTextChanged(AmountEditText.java:74)
我想确切地说错误不是来自我的onTextChanged因为一切都运行良好没有getText() override
编辑:用户可以输入数字,我会附加一些逗号来格式化数字。但是,当我覆盖getText()
时,我想以这种方式删除这些逗号,我不必每次都过滤getText()
的返回
在您的情况下,您不能覆盖getText()
并调整大小并同时使用TextWatcher
。
检查下面的android源代码,你会明白的原因
span那B了string builder.Java
public void setSpan(Object what, int start, int end, int flags) {
setSpan(true, what, start, end, flags, true/*enforceParagraph*/);
}
private void setSpan(boolean send, Object what, int start, int end, int flags,
boolean enforceParagraph) {
checkRange("setSpan", start, end);
}
private void checkRange(final String operation, int start, int end) {
...
int len = length();
if (start > len || end > len) {
throw new IndexOutOfBoundsException(operation + " " +
region(start, end) + " ends beyond length " + len); // here is you exception
}
}
public int length() {
return mText.length - mGapLength;
}
spell checker.Java
private void setRangeSpan(Editable editable, int start, int end) {
...
editable.setSpan(mRange, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
public void parse(int start, int end) {
...
if (parseEnd > start) {
setRangeSpan((Editable) mTextView.getText(), start, parseEnd); // I think the error happened from here, they use your getText() function here and receive shorter string, but the start, parseEnd still stick with original string
parse();
}
}
解决方案
您可以简单地定义像getBeautifulText()
这样的新函数。
好的,我调试了那个,发现问题就在那条线上
if (position == str.length()){
setSelection(finalStr.length());
}
lenght()
不受约束,因为它基于0
只需用它更改你的代码,它就能正常工作
if (position == str.length()){
setSelection(finalStr.length() - 1);
}
如果需要,这里有完整的代码(我使用了AppCompatEditText,但它是一样的):
public class AmountEditText extends android.support.v7.widget.AppCompatEditText {
@Override
public Editable getText() {
Editable s = super.getText();
if(s!=null && s.length()>0) {
if (s.toString().contains(",")) {
return new SpannableStringBuilder(s.toString().replace(",", ""));
}
}
return s;
}
private TextWatcher watcher = 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) {
int position = getSelectionStart();
int nbCommaBefore;
int nbCommaAfter;
String str = s.toString();
String finalStr;
String formattedStr;
nbCommaBefore = str.length() - str.replace(",", "").length();
boolean containsDot = false;
if (str.contains(".")) {
containsDot = true;
formattedStr = str.split("\\.")[0];
} else {
formattedStr = str;
}
if (!s.toString().isEmpty()) {
removeTextChangedListener(watcher);
formattedStr = formattedStr.replace(",", "");
formattedStr = formattedStr.replaceAll("(\\d)(?=(\\d{3})+$)", "$1,");
if (containsDot) {
if (str.split("\\.").length != 1) {
finalStr = formattedStr + "." + str.split("\\.")[1].replace(",", "");
} else {
finalStr = formattedStr + ".";
}
} else {
finalStr = formattedStr;
}
nbCommaAfter = finalStr.length() - finalStr.replace(",", "").length();
setText(finalStr);
if (position == str.length()){
setSelection(finalStr.length() - 1);
}
else if (position == 0)
{
setSelection(0);
}
else if (nbCommaBefore < nbCommaAfter){
setSelection(position + 1);
}
else if (nbCommaAfter < nbCommaBefore){
setSelection(position - 1);
}
else{
setSelection(position);
}
addTextChangedListener(watcher);
}
}
@Override
public void afterTextChanged(Editable s) {
}
};
public AmountEditText(Context context) {
this(context, null);
}
public AmountEditText(Context context, AttributeSet attrs) {
super(context, attrs);
addTextChangedListener(watcher);
}
public AmountEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
addTextChangedListener(watcher);
}
}
如果有帮助,请告诉我!
试试这个会对你有所帮助
editText.addTextChangedListener(new TextWatcher() {
boolean isEdiging;
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
if (isEdiging) return;
isEdiging = true;
String str = s.toString().replaceAll("[^\\d]", "");
double s1 = 0;
try {
s1 = Double.parseDouble(str);
} catch (NumberFormatException e) {
e.printStackTrace();
}
NumberFormat nf2 = NumberFormat.getInstance(Locale.ENGLISH);
((DecimalFormat) nf2).applyPattern("###,###.###");
s.replace(0, s.length(), nf2.format(s1));
if (s.toString().equals("0")) {
editText.setText("");
}
isEdiging = false;
}
});
根据您问题的要求:
用户可以输入数字,我会附加一些逗号来格式化数字。但是当我覆盖getText()时,我想删除这些逗号
我相信你可以使用一个更简单的解决方案,涉及DecimalFormat
:
class Formatter {
private final DecimalFormat f = new DecimalFormat(",###");
private final DecimalFormat o = new DecimalFormat("#");
String withCommas(String in) {
try {
return withCommas(Long.parseLong(in));
} catch (NumberFormatException e) {
e.printStackTrace();
return withCommas(Long.MIN_VALUE);
}
}
String withCommas(long in) {
return f.format(in);
}
Number stripCommas(String in) {
try {
return f.parse(in);
} catch (ParseException e) {
return Long.MIN_VALUE;
}
}
String stripCommasAsString(String in) {
return o.format(stripCommas(in));
}
}
这使:
final long num = 12345678L;
final Formatter f = new Formatter();
assertEquals("12,345,678", f.withCommas("12345678"));
assertEquals("12,345,678", f.withCommas(num));
assertEquals(num, f.stripCommas("12,345,678");
assertEquals("12345678", f.stripCommasAsString("12,345,678"));