2

I am trying to learn Android. I have some Java experience but have never seen a code block like this one:

        addNumsButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            EditText firstNumEditText = (EditText) findViewById(R.id.firstNumEditText);
            EditText secNumEditText = (EditText) findViewById(R.id.secNumEditText);
            TextView resultTextView = (TextView) findViewById(R.id.resultTextView);
            resultTextView.setText((Integer.parseInt(firstNumEditText.getText().toString()) + Integer.parseInt(secNumEditText.getText().toString())) + "");
        }
    });

What is getting declared after the View.OnClickListener()? I checked that View.OnClickListener() returns type Interface.

What does the code after that method is used for?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • "Android Studio" is only the IDE. Your question is not specific to that IDE and most of what you learn isn't specific to that IDE either. So mostly you learn about "Android", not about "Android Studio". – Joachim Sauer Nov 29 '20 at 16:42

1 Answers1

2

That's an anonymous class. It's special syntax for creating an instance of an abstract type by providing implementations right at the point of declaration. It's very common in GUI code (Android, Swing, what have you) to provide GUI action callbacks.

What your snippet is doing is pass an ad-hoc instance of View.OnClickListener to setOnClickListener that executes the code in the innermost brace block when the button is clicked.

OhleC
  • 2,821
  • 16
  • 29