Sena
Sena

Reputation: 298

android - substract edittext's text

Currently, I'm making a cashier app. I have an EditText which contains item(string) that is included in the shopping cart. I can add items by touching button. However now I just need a button to subtract the EditText by the latest inputted text to EditText.

For example, if I add milk(1$), sugar(0.8$), theEditText will show "milk + sugar". Then I want to remove the latest item that is sugar. So I touch delete button and I want now the EditText shows only milk. So it substracts "sugar" only. My brain no longer has any idea.

Note: TextView can replace EditText in this case.

And by the way, I can't show my code. I'm not bringing my laptop.

Last, if you have another way to remove not only the latest input, like I can delete the milk word even it's not the latest input, that's good:).

Thank you for your attention!:)

Upvotes: 0

Views: 39

Answers (1)

Neerajlal K
Neerajlal K

Reputation: 6828

Store the selected items in a List.

List<String> selectedItems = new ArrayList<String>();

Update the EditText as follows,

private void updateEditText() {
    StringBuilder text = new StringBuilder();
    for (int i = 0; i < selectedItems.size(); i++ ) {
        text.append(item);
        if(i != selectedItems.size() -1) {
            text.append(" + ");
        }
    }
    editText.setText(text.toString());
}

Method to add to selected List,

private void addItem(String item){
    // add some duplicate checking logic if needed

    // add the item to selected list
    selectedItems.add(item);

    // update the EditText
    updateEditText();
}

Method to remove item from selected List,

private void removeItem(String item){

    // remove the item from selected list
    selectedItems.remove(item);

    // update the EditText
    updateEditText();
}

For Example,

User selects "Milk" and "Sugar":

addItem("Milk");
addItem("Sugar");

User removes "Milk":

removeItem("Milk");

Hope it helps :)

Upvotes: 1

Related Questions