使用RecyclerView需要以下步驟:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> mData;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public ViewHolder(View v) {
super(v);
textView = v.findViewById(R.id.textview);
}
}
public MyAdapter(List<String> data) {
mData = data;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textView.setText(mData.get(position));
}
@Override
public int getItemCount() {
return mData.size();
}
}
RecyclerView recyclerView = findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
MyAdapter adapter = new MyAdapter(data); // data為要顯示的數據列表
recyclerView.setAdapter(adapter);
在上述代碼中,item_layout.xml
是每個RecyclerView項的布局文件,可以根據需要自定義。data
是要顯示的數據列表,可以根據需求進行修改。