RecyclerView是Android官方推薦的用于顯示大量數據的列表控件,相比ListView具有更好的性能和擴展性。下面是使用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<>();
// 添加數據到data
CustomAdapter adapter = new CustomAdapter(data);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
這樣就完成了一個簡單的RecyclerView的使用示例。在實際開發中,可以根據需求自定義Adapter和布局文件,實現更加復雜和豐富的列表展示效果。