Question

I've implemented a gridview and I've been hacking it together from examples to get a feel for how it works. I created and Adapter and when I came to implement the listener I discovered it is achieved like this.

private OnItemClickListener mColourClickListener = new OnItemClickListener() 
{
    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id){
        Log.d("LISTENER","Position Clicked ["+position+"]");
        }

};

Why is this different to a listview and why does it have it's methods implemented in braces after the variable declaration?

Many thanks,

M

Was it helpful?

Solution

You are creating new instance of anonymous class that implements OnItemClickListener interface. It is easier than defining new class and then creating new instance of this class. Anonymous class allows you to define class inline where you need it. Listeners are usually for one time use, so they are often defined as anonymous classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top