Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android setOnclicklistener parameter

Tags:

java

android

I'm a beginner to android, while setting onclick listener to a button, what does the parameter passed mean:

 btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    });    

so, "new OnClickListener()" it is passed to a method then shouldn't that be an object?
if it is not an object; then how do we use "new" keyword?
why "onclick()" is called directly without using the "this" keyword, or its class name.

like image 380
Ahmed Waheed Avatar asked Mar 14 '12 10:03

Ahmed Waheed


1 Answers

OnClickListener is an interface and by using new OnClickListener() as parameter for btn1.setOnClickListener it is actually creating an Anonymous Inner Class which implements OnClickListener. And the method onClick must need to be declared since its an abstract method inside that interface class. Any code you write inside onClick will be executed when the button is pressed.


Update

to do it using Anonymous inner class in an object:

//declaring OnClickListener as an object
private OnClickListener btnClick = new OnClickListener() {
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
};

//passing listener object to button
btn1.setOnClickListener(btnClick);

to do it without using Anonymous class:

public class YourActivity extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       Button b = new Button(this);

       //setting listener to button
       b.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
}

The only difference between these approaches is, if your button contains click event code which is supposed to be valid/available for that button only, then you may use inner class as you are doing in your code (because its easy to do right away). However if there are multiple buttons which require same code to be executed on onClick event then you may define listener as an object and pass it to them.

like image 200
waqaslam Avatar answered Oct 03 '22 14:10

waqaslam