Android RecyclerView Tutorial: Step-by-Step Guide
RecyclerView is a recommended official Android widget for displaying large amounts of data in a list, offering better performance and scalability compared to ListView. Here are the simple steps to use RecyclerView:
- Add a RecyclerView widget to the layout file.
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
- Create a custom Adapter that inherits from RecyclerView.Adapter and implement the necessary methods.
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private List<String> mData;
public CustomAdapter(List<String> data) {
this.mData = data;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.bind(mData.get(position));
}
@Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textView);
}
public void bind(String data) {
textView.setText(data);
}
}
}
- Create a layout file for displaying the style of each item (item_layout.xml):
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
- Initialize RecyclerView and set the Adapter in Activity or Fragment.
RecyclerView recyclerView = findViewById(R.id.recyclerView);
List<String> data = new ArrayList<>();
// 添加数据到data
CustomAdapter adapter = new CustomAdapter(data);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
This completes a simple example of using RecyclerView. In actual development, you can customize the Adapter and layout files according to your needs to achieve a more complex and rich list display effect.