0

I've just started learning Android development and as a little project, I'm building a calculator. The way it works is that when a number button is pressed, the number is appended to the EditText. I don't want to write this code for each of the buttons, because it's tedious and blatantly inefficient but i'm not sure how to go about it.

When I programmed in Java, I got around the problem by setting the ActionCommand of the JButton equal to the number and then making a general

textField.append(button.getActionCommand());

Is this possible in Android? Is there a better approach? Thanks for your help!

W.K.S
  • 9,787
  • 15
  • 75
  • 122

1 Answers1

2

You can add tag to every button. In onClick method retrieve tag from button and append it to edit box. OnClickListener for all number buttons will be the same:

public void onClick(View v) {
  String value = v.getTag();
  editText.getText().append(value);
}

So you can use 1 instance of OnClickListener for all buttons.

Mikita Belahlazau
  • 15,326
  • 2
  • 38
  • 43