将项动态添加到ListView的自定义适配器可以通过以下步骤实现:
public class CustomAdapter extends BaseAdapter {
private List<String> itemList;
private Context context;
public CustomAdapter(Context context, List<String> itemList) {
this.context = context;
this.itemList = itemList;
}
@Override
public int getCount() {
return itemList.size();
}
@Override
public Object getItem(int position) {
return itemList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.itemTextView = convertView.findViewById(R.id.item_text_view);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String item = itemList.get(position);
holder.itemTextView.setText(item);
return convertView;
}
private static class ViewHolder {
TextView itemTextView;
}
}
ListView listView = findViewById(R.id.list_view);
List<String> itemList = new ArrayList<>();
CustomAdapter adapter = new CustomAdapter(this, itemList);
listView.setAdapter(adapter);
itemList.add("新项");
adapter.notifyDataSetChanged();
这样,新项就会动态地添加到ListView中。
自定义适配器的优势在于可以根据需求自由定制列表项的布局和样式,以及处理列表项的点击事件等。适用场景包括但不限于:
腾讯云提供的相关产品和产品介绍链接地址如下:
领取专属 10元无门槛券
手把手带您无忧上云