[android] Android setOnClickListener method - How does it work?

I have trouble understanding this code. I get that findViewById will get the button widget and then it'll cast it. Then, it's going to use the button to call the setOnClickListener method. However, I don't know what is that argument being passed into the setOnClickListener and I have never seen code like that before. How is it that it creates a new object but is able to create a method of its own within another method's argument? Would be great if someone could explain that. Also, what type of object is the setOnClickListener method taking in?

btn = (Button)findViewById(R.id.firstButton);
btn.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        tv.setText(months[rand.nextInt(12)]);
        tv.setTextColor(Color.rgb(rand.nextInt(255)+1, rand.nextInt(255)+1, rand.nextInt(255)+1));
    }
});

This question is related to android button onclicklistener

The answer is


It works by same principle of anonymous inner class where we can instantiate an interface without actually defining a class :

Ref: https://www.geeksforgeeks.org/anonymous-inner-class-java/


its an implementation of anonymouse class object creation to give ease of writing less code and to save time


This is the best way to implement Onclicklistener for many buttons in a row implement View.onclicklistener.

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

This is a button in the MainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    bt_submit = (Button) findViewById(R.id.submit);

    bt_submit.setOnClickListener(this);
}

This is an override method

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.submit:
                //action

                break;

            case R.id.secondbutton:
                //action
                break;
        }
    }

That what manual says about setOnClickListener method is:

public void setOnClickListener (View.OnClickListener l)

Added in API level 1 Register a callback to be invoked when this view is clicked. If this view is not clickable, it becomes clickable.

Parameters

l View.OnClickListener: The callback that will run

And normally you have to use it like this

public class ExampleActivity extends Activity implements OnClickListener {
    protected void onCreate(Bundle savedValues) {
        ...
        Button button = (Button)findViewById(R.id.corky);
        button.setOnClickListener(this);
    }

    // Implement the OnClickListener callback
    public void onClick(View v) {
      // do something when the button is clicked
    }
    ...
}

Take a look at this lesson as well Building a Simple Calculator using Android Studio.


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to button

How do I disable a Button in Flutter? Enable/disable buttons with Angular Disable Button in Angular 2 Wrapping a react-router Link in an html button CSS change button style after click Circle button css How to put a link on a button with bootstrap? What is the hamburger menu icon called and the three vertical dots icon called? React onClick function fires on render Run php function on button click

Examples related to onclicklistener

Android - setOnClickListener vs OnClickListener vs View.OnClickListener Null pointer Exception on .setOnClickListener Multiple Buttons' OnClickListener() android Android setOnClickListener method - How does it work? RecyclerView onClick How do I open a new fragment from another fragment? Why is this jQuery click function not working? Android button onClickListener Android: how to handle button click Adding an onclicklistener to listview (android)