Search code examples
androidtextviewgettextsettext

Get info from view that triggered onclick?


I'm completely new to Java and android. I ended a tutorial and I'm building a simple calculator to learn the ropes.

I basically have a view like this:

<button android:onClick="addText" android:text="2" />

And function addText is this:

public void addText(View view) { // Add view's text
    TextView calc = (TextView) findViewById(R.id.edit_text);
    t.setText( calc.getText() + ????? );
}

onclick it should add the text from the clicked button to a TextView. If you click 1, it does calc.getText() + "1" if you click 2 it does calc.getText() + "2". I don't know how to get the clicked view's text. I tried this: t.setText( calc.getText() + this.getText() ); which didn't work. How is this done?


Solution

  • You can do this:

    public void addText(View view) { // Add view's text
      Button button = (Button) view; //casts the View into the Button class
      TextView calc = (TextView) findViewById(R.id.edit_text);
      t.setText(calc.getText().toString() + button.getText().toString());
    }
    

    Since we know that Button is a subclass of View, and the getText() method works with buttons, we can make a new variable and turn the View parameter into a Button, via class casting. From there we can use all the Button's methods and continue with execution.