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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With