Search code examples
javaandroidparameter-passingonclicklistener

Passing an object of MainActivity through View.OnClickListener()


Below is an example of My app's MainActivity.java:

/*imports and other stuffs*/

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

Button myButton;

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

    myButton = (Button) findViewById(R.id.first_button);
   // myButton.setOnClickListener(this); by using it, app works as desired.


    myButton.setOnClickListener(new MainActivity()); //What's wrong with this piece of codes?

}

@Override
public void onClick(View v) {
    if(v.getId()==R.id.first_button){
        Toast.makeText(this, "Made it", Toast.LENGTH_SHORT).show();
    }

}

As setOnClickListener() method requires an object of a class that implements View.setOnClickListener, it can be handled with a custom class implements View.setOnClickListener, but my question, as a beginner, is what's going on actually, while passing an object of MainActivity?

Edit:

But if I pass an object of another class and pass that one, the code works perfectly, doesn't it? and what about those codes:

public class MainActivity extends AppCompatActivity {
Button myButton;

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

    myButton = (Button) findViewById(R.id.first_button);


    myButton.setOnClickListener(new MyClass());


}

class MyClass implements View.OnClickListener{

    @Override
    public void onClick(View v) {
        Log.d("buttontest","Working Perfectly");
    }
}

}


Solution

  • myButton.setOnClickListener(new MainActivity());
    

    With that piece of code you are setting on OnClickListener for your myButton. However, you are not creating the correct listener object. You are creating a new MainActivity object that is not the correct type.

    myButton.setOnClickListener(this);
    

    This is correct, because the class implements View.OnClickListener and has the implementation with the void onClick(View v) method in the class.

    You can also do this if you like too:

    myButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // add code here
                }
            });
    

    This will create an new OnClickListener object with the onClick method implemented as well. This is passing an anonymous class to the setOnClickListener.