-4

I am new to ANDROID DEVELOPMENT. I learnt java before jumping in to Android. I see this code in a book and I am stumped. How does this even work?

I get the part that the setbutton method of progressDialog class is receiving parameters.

But the 3rd parameter is a class? I though new keyword is used to create a new type (a class). how is that a method (.OnClickListener) is being referenced when the class is being created on top of all, there is another method(onClick) being created inside it. Obviously, there is something in java I am not aware of. Can someone tell me if there is a tutorial on this concept in java? I am not worried about a button being created and being clicked on. I am talking about the concept of this programming used in here.

Thank you so much.

progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, “OK”,
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int whichButton)
        {
            Toast.makeText(getBaseContext(),“OK clicked!”, 
                Toast.LENGTH_SHORT).show();
        }
});
Hannoun Yassir
  • 20,583
  • 23
  • 77
  • 112
user1666952
  • 309
  • 1
  • 8
  • 18

2 Answers2

1

This is not related to android as much as it is related to JAVA anyway it is called anonymous inner class

Hannoun Yassir
  • 20,583
  • 23
  • 77
  • 112
  • Yes I know. That's why I mentioned I found the code in Android and I need some guidance learn the concept of this. Thanks for all the classes. I realized it would be a case similar to javascript passing functions as a parameter to another function. – user1666952 Sep 27 '13 at 13:24
1

An anonymous inner class can come useful when making an instance of an object which certain "extras" such as overloading methods, without having to actually subclass a class.

progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, “OK”,
new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog,int whichButton)
    {
        Toast.makeText(getBaseContext(),“OK clicked!”, 
            Toast.LENGTH_SHORT).show();
    }
});

Instead of above code, u could also declare as follows but its bit long to code.

progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "ok", new DialogDemo());

By writing the inner class like as follows

private class DialogDemo implements DialogInterface.OnClickListener{

    @Override
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(getBaseContext(),“OK clicked!”, 
                Toast.LENGTH_SHORT).show();
}
}
Balaji Dhanasekar
  • 1,066
  • 8
  • 18