'Button for backspace for calculator in Android
I'm developing a calculator in which I want to add a backspace button. On clicking on backspace button elements of EditText will be delete one-by-one. But I'm not getting how to write the code for this. Please suggest a solution?
Solution 1:[1]
Something like this should work:
EditText edit;
...
String txt = edit.getText();
txt = txt.length() > 1 ? txt.substring(0, txt.length() - 2) : "0";
edit.setText(txt);
Solution 2:[2]
binding.idImageViewBackSpace.setOnClickListener {
val CursorPos = binding.InputTextView.selectionStart
val length = binding.InputTextView.text.length
if (CursorPos != 0 && length != 0) {
val selection: Editable? = binding.InputTextView.text
selection?.replace(CursorPos - 1, CursorPos, "")
binding.InputTextView.text = selection
binding.InputTextView.setSelection(CursorPos - 1)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aleks G |
| Solution 2 | Abhinav Dwivedi |
