Implements method in Adapter in RecyclerView (androidx.recyclerview.widget)
时间: 2023-10-30 19:11:49 浏览: 125
To implement a custom Adapter in RecyclerView, you need to follow these steps:
1. Create a new class that extends RecyclerView.Adapter. This class will act as the adapter for your RecyclerView.
2. Override the onCreateViewHolder method, which is responsible for creating the ViewHolder objects for each item in the RecyclerView. In this method, you need to inflate the layout for the item and create a new ViewHolder object that holds a reference to the views in the layout.
3. Override the onBindViewHolder method, which is responsible for binding the data to the views in the ViewHolder object. In this method, you need to get the data for the current item and set it to the views in the ViewHolder object.
4. Override the getItemCount method, which returns the total number of items in the RecyclerView.
Here's an example code snippet for implementing a custom Adapter in RecyclerView:
```
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> mData;
public MyAdapter(List<String> data) {
mData = data;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_item_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String item = mData.get(position);
holder.mTextView.setText(item);
}
@Override
public int getItemCount() {
return mData.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public ViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.text_view);
}
}
}
```
In this example, the MyAdapter class extends RecyclerView.Adapter and takes a list of strings as data in its constructor. The onCreateViewHolder method inflates the layout for each item from a layout resource file and creates a new ViewHolder object. The onBindViewHolder method sets the text for each item in the RecyclerView. Finally, the getItemCount method returns the total number of items in the RecyclerView.
Note that in this example, the ViewHolder class is defined as a static inner class of the MyAdapter class. This is a common practice to keep the code organized and to avoid memory leaks.
阅读全文