简体   繁体   English

在Android中传递MainActivity作为参数RecyclerView Adapter

[英]Passing MainActivity as a parameter RecyclerView Adapter in android

I am following this android tutorial 我正在关注这个Android教程

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 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. 为了处理RecyclerView.Adapter(本教程中的实例GreenAdapter)中的项目单击,我们创建了一个接口来接收来自活动的onclick消息。 We then implement the interface in the MainActivity by overriding onListItemClick. 然后,我们通过重写onListItemClick在MainActivity中实现该接口。 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. 是指活动实例,但是GreenAdapter构造函数采用ListItemClickListener类型。

How is this possible. 这怎么可能。 How can an Activity be passed/cast as ListItemClickListener type. 如何将Activity作为ListItemClickListener类型传递/投射。

Here this means that your MainActivity has the implementation of the ListItemClickListener . 在这里, this意味着您的MainActivity具有ListItemClickListener的实现。 Read the documentation of the Android from the official documentation. 从官方文档中阅读Android的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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