我有一个Edittext,并希望设置EditText,以便当用户输入要转换的数字时,应实时自动将一千个分隔符(,)自动添加到数字中。但是我想在“ onTextChanged”中执行此操作”方法不在“ afterTextChanged”方法中。我该怎么办?
rebase -i <after-this-commit>
}
答案 0 :(得分:1)
尝试以下代码:
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);
}
});
答案 1 :(得分:1)
我使用TextWatcher
来触发EditText
中的每次更改,并使用此代码来分隔货币部分,然后在每次字符更改后将其设置为EditText:
public static String formatCurrencyDigit(long amount) {
return String.format("%,d%s %s", amount, "", "");
}