在Android中,RecyclerView是用于顯示大量數據的高性能容器。以下是使用RecyclerView的步驟:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public MyViewHolder(View view) {
super(view);
textView = view.findViewById(R.id.textView);
}
}
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private List<String> data;
public MyAdapter(List<String> data) {
this.data = data;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
String item = data.get(position);
holder.textView.setText(item);
}
@Override
public int getItemCount() {
return data.size();
}
}
RecyclerView recyclerView = findViewById(R.id.recyclerView);
List<String> data = new ArrayList<>();
// 添加數據到data中
MyAdapter adapter = new MyAdapter(data);
recyclerView.setAdapter(adapter);
這樣就完成了RecyclerView的基本使用。你可以使用不同的布局文件和自定義ViewHolder來實現更復雜的列表項布局。