QUOTE(narf03 @ Nov 9 2018, 05:21 AM)
CODE
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});
in the code above, it create a new "OnItemClickListener() " then instantly have to create the function body, how do i tell it to use other function ? like i have 2 listview that perform the same thing, i dont want to duplicate the code twice, so i create a function, then pass this function into the 2 listview's setOnItemClickListener
This is a textbook implementation of an Anonymous Class. It's a legitimate style to use when that particular implementation of "OnItemClickListener" has no intention of being used elsewhere.
You have to "instantly create the function body" because, in actuality what's going on here is:
1. A new anonymous class that extends "OnItemClickListener" is being defined.
1a. "OnItemClickListener" may be an interface or abstract class, that cannot be instantiated into an object until the abstract method "onItemClick" is defined.
2. The anonymous class is instantiated into an object by the "new" operator, and the object is injected into the listView via a setter method.
If there were multiple "listView" in the same Java class that you wanted to have the same "onItemClick" behaviour, you can pass around the same OnItemClickListener object by giving it a handle (by assigning it to a variable). This was the solution suggested by alphasp.
However, if the many "listView" are in different classes (.java files), you'd want to promote the OnItemClickListener implementation into a standalone class, as suggested by life4.
Some Java concepts to take away here:
1. Classes vs Objects
2. Abstract types such as Interfaces and Abstract Classes
3. Nested Classes (the category that Anonymous Classes belong to)
4. Polymorphism and Encapsulation, which are the main OO concepts at play here.