Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setOnClickListener(new OnClickListener(){})

Tags:

java

android

package android.example;

import android.app.Activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class Android_eg1 extends Activity {
    Button bt; 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        bt=(Button)findViewById(R.id.click);
        bt.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
            // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "You made a mess", Toast.LENGTH_LONG).show();
            }

        });
      } //onCreate()

}//class

I am new to java and I know basics of core java. This is the sample program i tried to know about the event handling through a button class. I could not understand this part :

"bt.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
        // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "You made a mess", Toast.LENGTH_LONG).show();
        }

    });"

Inside the setOnClickListener(parameter) why are they giving a function definition?(public void onClick(View v) })

Is this acceptable?

like image 703
Angus Avatar asked Mar 06 '12 03:03

Angus


1 Answers

In java, this is a Generated Class implementing the interface. You can generate a class on the fly inside the function argument or you can create an external class and passing a instance of this class or implements the Interface needed by your listener by your activty and passing your activity as listener.

like image 109
Pascal Piché Avatar answered Nov 05 '22 15:11

Pascal Piché