RecyclerView是Android中用于顯示大量數據列表的控件,它是ListView的升級版。使用RecyclerView需要以下幾個步驟:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> mData;
public MyAdapter(List<String> data) {
mData = data;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
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(R.id.text_view);
}
}
}
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
List<String> data = new ArrayList<>();
data.add("Item 1");
data.add("Item 2");
// ...
MyAdapter adapter = new MyAdapter(data);
recyclerView.setAdapter(adapter);
這樣就完成了RecyclerView的基本使用。你可以根據需要自定義Adapter和列表項的布局,以及設置點擊事件等。