Simple steps to use Android RecyclerView

Basic usage steps of Android RecyclerView (course review)

1. Before using RecyclerView, you need to add dependencies in the Gradle file

implementation ‘com.android.support:recyclerview-v7:25.4.0’

2. Add the required RecyclerView elements in the xml

<android.support.v7.widget.RecyclerView
android:id=”@+id/recyclerview_forecast”
android:layout_width=”match_parent”
android:layout_height=”match_parent”/>

3. Set the xml style for the elements inside the RecyclerView

In addition, create an xml file to define the style of the elements in the list

4. Create a class that inherits from RecyclerView.Adapter<MyAdapter.MyViewHolder>

MyAdapter is the created class, MyViewHolder is the inner class of the created MyAdapter class, this inner class needs to inherit from RecyclerView.ViewHolder;
in MyViewHolder, the onCreateViewHolder method needs to be rewritten, this method is called when the ViewHolder is created, and the RecyclerView display is will create enough ViewHolders to display;
specific sample code:

@Override
public ForecastAdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
Context context = viewGroup.getContext();
int layoutIdForListItem = R.layout.forecast_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater .inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
return new ForecastAdapterViewHolder(view);
}
where layoutIdForListItem is the id of the view style previously created for the elements in the list; others remain unchanged

Secondly, you need to rewrite the onBindViewHolder method, which is used to display the data in the corresponding position (for example, use the setText() method of TextView to set the content for the TextView);

Finally, you need to override the getItemCount method, which returns the number of list elements to be displayed;

5. Instantiate RecyclerView, set Adapter and LayoutManager for RecyclerView object (select LinearLayoutManager here)

Sample code:

mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_forecast);
LinearLayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
mForecastAdapter = new ForecastAdapter();
mRecyclerView.setAdapter(mForecastAdapter);

Beginning to learn Android, please point out any errata, O(∩ ∩)O thank you )

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324729995&siteId=291194637
Recommended