ListView控件添加数据的方法有两种:
ListView listView = findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
adapter.add("Item 1");
adapter.add("Item 2");
listView.setAdapter(adapter);
public class MyAdapter extends BaseAdapter {
private List<String> mData;
public MyAdapter(List<String> data) {
mData = data;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// 创建或重用convertView,并设置数据
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.textView = convertView.findViewById(R.id.textView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.textView.setText(mData.get(position));
return convertView;
}
private static class ViewHolder {
TextView textView;
}
}
// 在Activity中使用适配器
ListView listView = findViewById(R.id.listView);
List<String> data = new ArrayList<>();
data.add("Item 1");
data.add("Item 2");
MyAdapter adapter = new MyAdapter(data);
listView.setAdapter(adapter);
以上是两种常用的添加数据的方法,你可以根据具体需求选择适合的方法。