RecyclerView是Android官方推薦的用于顯示大量數(shù)據(jù)的列表控件,相比ListView具有更好的性能和擴(kuò)展性。下面是使用RecyclerView的簡單步驟:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
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);
}
}
}
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
RecyclerView recyclerView = findViewById(R.id.recyclerView);
List<String> data = new ArrayList<>();
// 添加數(shù)據(jù)到data
CustomAdapter adapter = new CustomAdapter(data);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
這樣就完成了一個(gè)簡單的RecyclerView的使用示例。在實(shí)際開發(fā)中,可以根據(jù)需求自定義Adapter和布局文件,實(shí)現(xiàn)更加復(fù)雜和豐富的列表展示效果。