RThomP RThomP - 1 month ago 9
Android Question

Android - deleting characters on button press

Below is the method I've coded to input numbers for a calculator. The code is fully functional and is error-free.

I'm trying to figure out how I would write a separate method called

backspace
to remove one character at a time from the user input.

To give an example of how
onClick1
works (just to make it crystal clear what I want to do), if I entered
2+4*6
(using buttons; their onClick action linked to
onClick1
), then
textViewCalcHistExp1
would display the text
2+4*6
, and
arrayList
would hold the following values:
[2,+,4,*,6]
.

I want
backspace
to work so that if I clicked the button (linked with the
backspace
method),
textViewCalcHistExp1
's display would now be
2+4*
and
arrayList
would now hold the following values:
[2,+,4,*]
.

Here is the code:

ArrayList<String> arrayList = new ArrayList<String>();
String stringInput = "";
String stringInputWithOp = "";
public String prevCalc = "";

public void onClick1 (View view) {
TextView textViewCalcHistExp1 = (TextView) findViewById(R.id.textViewCalcHistExp1);
Button button = (Button) view;
stringInput = (String) button.getText().toString();


if (!stringInput.contains("+") && !stringInput.contains("-") && !stringInput.contains("×") && !stringInput.contains("÷")) {
stringInputWithOp = stringInputWithOp+stringInput;
if (arrayList.size()>0) {
arrayList.remove((arrayList.size()-1));
}
arrayList.add(stringInputWithOp);
}
else {
arrayList.add(stringInput);
arrayList.add(stringInput);
stringInputWithOp="";
}
//This version truncates array formatting i.e. entering "2+4*6" would display "2+4*6"
textViewCalcHistExp1.setText(textViewCalcHistExp1.getText().toString()+stringInput);

//This version leaves array formatting i.e. entering "2+4*6" would display [2,+,4,*,6] ;good for debugging
//textViewCalcHistExp1.setText(arrayList.toString());
}

Answer

You could do something like this:

private void backspace() {
    if (!arrayList.isEmpty()) {
        // removing the last item from the ArrayList
        arrayList.remove(arrayList.size() - 1);
    }

    String string = textViewCalcHistExp1.getText().toString();
    if(string.length() > 0) {
        // removing the last character from the TextView
        textViewCalcHistExp1.setText(string.substring(0, string.length() - 1));
    }
}

You'd also need to make textViewCalcHistExp1 an instance variable (arrayList already is), by declaring it outside onClick1().

Comments