在 Android 中,要动态加载列表项,通常使用 ListView 或 RecyclerView。这里以 RecyclerView 为例,介绍如何动态加载列表项。
dependencies {
implementation 'com.android.support:recyclerview-v7:28.0.0'
}
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
public class Item {
private String title;
public Item(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
public TextView titleTextView;
public ItemViewHolder(View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.title_text_view);
}
}
public class ItemAdapter extends RecyclerView.Adapter<ItemViewHolder> {
private List<Item> itemList;
public ItemAdapter(List<Item> itemList) {
this.itemList = itemList;
}
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new ItemViewHolder(itemView);
}
@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
Item currentItem = itemList.get(position);
holder.titleTextView.setText(currentItem.getTitle());
}
@Override
public int getItemCount() {
return itemList.size();
}
}
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
// 设置布局管理器
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
// 准备数据
List<Item> itemList = new ArrayList<>();
for (int i = 1; i <= 20; i++) {
itemList.add(new Item("Item " + i));
}
// 设置 Adapter
adapter = new ItemAdapter(itemList);
recyclerView.setAdapter(adapter);
}
}
这样,列表项就会根据数据源动态加载。如果需要更新数据,只需修改 itemList 并调用 adapter.notifyDataSetChanged() 即可。