将列表项动态添加到RecyclerView可以通过以下步骤实现:
以下是一个示例代码:
// 1. 初始化RecyclerView
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// 2. 创建数据源
List<String> dataList = new ArrayList<>();
// 3. 创建适配器
MyAdapter adapter = new MyAdapter(dataList);
// 4. 创建列表项布局(list_item.xml)
// ...
// 5. 实现适配器方法
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> mDataList;
public MyAdapter(List<String> dataList) {
mDataList = dataList;
}
@Override
public int getItemCount() {
return mDataList.size();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String data = mDataList.get(position);
holder.textView.setText(data);
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textView);
}
}
}
// 6. 添加列表项
dataList.add("Item 1");
adapter.notifyDataSetChanged();
// 7. 更新RecyclerView
recyclerView.setAdapter(adapter);
这样,当调用dataList.add("Item 1")
并调用adapter.notifyDataSetChanged()
后,RecyclerView会动态添加一个新的列表项,并更新显示。
领取专属 10元无门槛券
手把手带您无忧上云