我要覆盖getText()
的EditText。
我收到这种字符串:"12,345,678"
我的目的是删除逗号并返回Editable,但是当我的代码出现错误时。
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)结束于 长度4 在android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1265) 在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.SpellChecker.spellCheck(SpellChecker.java:242) 在android.widget.Editor.updateSpellCheckSpans(Editor.java:679) 在android.widget.Editor.sendOnTextChanged(Editor.java:1249) 在android.widget.TextView.sendOnTextChanged(TextView.java:8191) 在android.widget.TextView.setText(TextView.java:4483) 在android.widget.TextView.setText(TextView.java:4337) 在android.widget.EditText.setText(EditText.java:89) 在android.widget.TextView.setText(TextView.java:4312) 在org.newtonproject.newpay.widgetlib.AmountEditText $ 1.onTextChanged(AmountEditText.java:74)
我想精确地指出错误不是来自于我的onTextChanged
因为在没有getText() override
编辑:用户可以输入数字,我将添加一些逗号以格式化数字。但是,当我覆盖getText()
时,我想以这种方式删除这些逗号,而不必每次都过滤getText()
的返回值
答案 0 :(得分:2)
好,我调试了一下,发现问题出在那条线上
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);
}
}
让我知道是否有帮助!
答案 1 :(得分:1)
根据您的情况,您无法覆盖getText()
并同时调整大小和使用TextWatcher
。
检查下面的android源代码,您将为什么
SpannableStringBuilder.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;
}
SpellChecker.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()
。
答案 2 :(得分:0)
尝试这个将对您有帮助
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;
}
});
答案 3 :(得分:0)
根据您的问题要求:
用户可以输入数字,我将添加一些逗号以 格式化数字。但是当我覆盖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"));