I am trying format a value entered in an EditText
, this must happen immediately, ie as soon as the user enters value into the EditText
, the application must format the value and set it to the EditText
again. My code is not correct and i can't find any way to format number on time
transfer_amount.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable charSequence) {
if (charSequence.toString().length() == 1 && charSequence.toString().equals("0")) {
transfer_amount.setText("");
} else if (charSequence.toString().length() > 0 && (int) charSequence.toString().charAt(0) >= 48 && (int) charSequence.toString().charAt(0) <= 57) {
Locale swedish = new Locale("sv", "SE");
NumberFormat swedishFormat = NumberFormat.getCurrencyInstance(swedish);
transfer_amount.setText(swedishFormat.format(Long.parseLong((charSequence.toString()))));
}
}
});
public void onTextChanged(CharSequence s, int start, int before, int count) {
long enteredNumber = Long.parseLong(s.toString().replace(",", ""));
transfer_amount.removeTextChangedListener(this);
DecimalFormat formatter = new DecimalFormat("#,###,###");
String yourFormattedString = formatter.format(enteredNumber);
Log.e("yourFormattedString ", yourFormattedString);
transfer_amount.setText(yourFormattedString);
transfer_amount.addTextChangedListener(this);
}
this code work until format number, when formatted my EditText cleared and i dont know whats problem,
My Log:
E/yourFormattedString: 1
E/yourFormattedString: 11
E/yourFormattedString: 111
E/yourFormattedString: 1,111
E/yourFormattedString: 1
For text change runtime you need to take care about the original string and modified string.
tt = new TextWatcher() {
public void afterTextChanged(Editable s) {
if(s.length()!=0) {
long enteredNumber = Long.parseLong(s.toString().replace(",", ""));
nameEdit.removeTextChangedListener(this);
DecimalFormat formatter = new DecimalFormat("#,###,###");
String yourFormattedString = formatter.format(enteredNumber);
Log.e("yourFormattedString ", yourFormattedString);
nameEdit.setText(yourFormattedString);
nameEdit.addTextChangedListener(this);
nameEdit.setSelection(yourFormattedString.length());
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
nameEdit.addTextChangedListener(tt);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.