Implements method in Adapter in RecyclerView (androidx.recyclerview.widget)
时间: 2023-10-30 19:11:49 浏览: 73
RecyclerViewAdapter
To implement an Adapter in RecyclerView, you need to follow these steps:
1. Create a new class that extends RecyclerView.Adapter and implements the required methods.
2. Override the onCreateViewHolder method to inflate the layout for each item in the list.
3. Override the onBindViewHolder method to bind the data to the views in the layout.
4. Override the getItemCount method to return the number of items in the list.
Here's an example code snippet to help you get started:
```java
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.textView.setText(item);
}
@Override
public int getItemCount() {
return mData.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public ViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
}
}
}
```
In this example, we have created a simple adapter that displays a list of strings. The onCreateViewHolder method inflates a layout file called "my_item_layout.xml", which contains a TextView. The onBindViewHolder method sets the text of the TextView to the corresponding item in the list. Finally, the getItemCount method returns the size of the list.
阅读全文