I am following this android tutorial
In order to handle item clicks in the RecyclerView.Adapter which is the instance GreenAdapter in the tutorial, we create an interface to receive onclick messages from the activity. We then implement the interface in the MainActivity by overriding onListItemClick. The code is shown below
public class GreenAdapter extends RecyclerView.Adapter<GreenAdapter.NumberViewHolder> {
public interface ListItemClickListener {
void onListItemClick(int clickedItemIndex);
}
final private ListItemClickListener mOnClickListener;
public GreenAdapter(int numberOfItems, ListItemClickListener listener) {
mNumberItems = numberOfItems;
mOnClickListener = listener;
viewHolderCount = 0;
}}
and the activity
public class MainActivity extends AppCompatActivity implements GreenAdapter.ListItemClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new GreenAdapter(NUM_LIST_ITEMS, this);}
The this is referring to the activity instance, but the GreenAdapter constructor takes a ListItemClickListener type.
How is this possible. How can an Activity be passed/cast as ListItemClickListener type.
Here this
means that your MainActivity
has the implementation of the ListItemClickListener
. Read the documentation of the Android from the official documentation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.