How to use Android to support the RecyclerView framework
How to use Android to support the RecyclerView framework
RecyclerView is a powerful list display control on the Android platform that can be used to display a large number of data items, such as contact lists, chat records, etc.Compared with ListView, RecyclerView has higher flexibility and scalability.Here are methods and examples of using the RecyclerView framework.
1. Add dependence
First, in the built.gradle file of the project, add RecyclerView dependencies:
dependencies {
implementation 'androidx.recyclerview:recyclerview:1.2.0'
}
Second, layout file
In the layout file that needs to be displayed, add the RecyclerView control:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
3. adapter class
Create an Adapter class that inherits RecyclerView.Adapter to process data and create a list of viewpoint views.The following is an example:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> mData;
public MyAdapter(List<String> data) {
this.mData = data;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// Create a list item view
View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
// Bind data to the list item view
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(@NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(android.R.id.text1);
}
}
}
Fourth, setting layoutManager and adapter
In Activity or Fragment, find the RecyclerView control and set the layoutManager and Adapter:
RecyclerView recyclerView = findViewById(R.id.recyclerView);
RecyclerView.setLayoutManager (New LinearlayoutManager (this)); // Set the layout manager
List <string> data = New ArrayList <> (); // Assuming a list of data
data.add("Item 1");
data.add("Item 2");
data.add("Item 3");
MyAdapter adapter = new MyAdapter(data);
RecyclerView.setAdapter (adapter); // Set the adapter
The above is the basic method and example of using the RecyclerView framework.By creating the adapter class, binding data to the list item view, and then setting the layoutManager and Adapter, you can easily use RecyclerView to display the list data in the Android application.