简体   繁体   中英

Passing MainActivity as a parameter RecyclerView Adapter in android

I am following this android tutorial

https://github.com/udacity/ud851-Exercises/blob/student/Lesson03-Green-Recycler-View/T03.07-Solution-RecyclerViewClickHandling/app/src/main/java/com/example/android/recyclerview/MainActivity.java

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM