Sajan
Sajan

Reputation: 97

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?

Upvotes: 1

Views: 2932

Answers (2)

SKYRELA
SKYRELA

Reputation: 31

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)
        }
    }

Upvotes: 0

Aleks G
Aleks G

Reputation: 57336

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);

Upvotes: 2

Related Questions