I would like to have an edit text that would automatically input a dollar sign before the number. Android Studio
Example $500
EDIT:
The addition of the $ should take place when the edit text is used (when tapped). The Currency will be in CAD. However the dollar sign will act as a reminder for what the field is
Just add an onChange listener and insert the $ after the user is done input.
private EditText yourEditText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
yourEditText = (EditText) findViewById(R.id.yourEditTextId);
yourEditText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
yourEditText.setText("$" + yourEditText.getText().toString());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
}
My solution unsing kotlin and databinding (but actually the essence is in the text watcher):
XML Part:
<EditText
...
android:addTextChangedListener="@{viewModel.currencyTextWatcher}"
android:inputType="number"
android:digits="$1234567890"
/>
TextWatcher implementation:
val currencyTextWatcher = object : TextWatcher {
override fun afterTextChanged(editable: Editable?) {
when {
editable.isNullOrEmpty() -> return
Regex("\\$\\d+").matches(editable.toString()) -> return
editable.toString() == "$" -> editable.clear()
editable.startsWith("$").not() -> editable.insert(0, "$")
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With