Question

I'm new to java and android. i don't understand this code

    gridview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
        }
    }); 

this's my guess : OnItemClickListener is an interface. we create an anonymous object from the class AdapterView. i got information that AdapterView.OnItemClickListener is an interface from AdapterView.OnItemClickListener

is it right ?

Was it helpful?

Solution

Yes essentially this mechanism gives you a way to specify a block of code that will get run whenever the event happens. In this case the event is an onItemClick() for a GridView. This pattern is used somewhat commonly on Android. You override the interface methods to do whatever you want, the system will call them when the action has taken place.

I would encourage you to explore some more common examples of this pattern in the Android APIs. Look at the javadocs for several of the View widgets, in particular the public void setOn{ACTION}Listener() There are many possible actions, click and touch are two common ones.

check out android.wiget in the docs. There is a big list of interfaces near the top. Several of them are Listener interfaces similar to this.

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