Answer the question
In order to leave comments, you need to log in
Input in EditText. How do I add a dollar sign at the end of a number when entering a number?
Hello. I am writing a currency converter. I want to make sure that when entering the amount, a dollar sign is added at the end. Tried to do via "TextWatcher" :
final EditText enter = (EditText) findViewById(R.id.enter);
final TextView result = (TextView) findViewById(R.id.result);
enter.addTextChangedListener(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)
{
}
@Override
public void afterTextChanged(Editable s)
{
if(enter.getText().length()!=0)
{
String ss= enter.gettext().toString();
ss= ss + "$";
enter.settext(ss);
}
else
{
result.setText(null);
}
}
});
Answer the question
In order to leave comments, you need to log in
As ivanfenenko said, the problem is in recursion. Do this:
enter.addTextChangedListener(new TextWatcher() {
private boolean mFormating;
@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) {
if (!mFormating) {
mFormating = true;
if(enter.getText().length() != 0) {
String ss= s.toString();
if (!ss.endsWith("$")) {
ss= ss + "$";
enter.setText(ss);
}
} else {
result.setText(null);
}
mFormating = false;
}
}
});
Wouldn't it be easier to make an icon next to the EditText? What happens if the user puts the correction at the end and continues to enter numbers? I think you chose not a very good way
Well, it’s really trouble with the correction, but you can make it so that it can delete this character, and then when it enters the amount again, it will appear again (or as soon as they start deleting, the correction jumps and deletes the numbers before the text)
Overrided
public void afterTextChanged(Editable s) {
Log.d(TAG, "AFTER");
if(!TextUtils.isEmpty(s)) {
if (!(s.charAt(s.length() - 1) == '$')) {
String dollarSign = s.toString() + '$';
etName.setText(dollarSign);
}
}
}
Basically what's going on here. Can't add characters to Editable in AfterTextChanged. Because as soon as this is done, it again calls all the methods and so cyclically and therefore a message flies out there
Regarding the code, as soon as someone enters the amount, this symbol will immediately be added to it (I didn’t do it so that it could be deleted, if it doesn’t work out, I’ll add the code)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question