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);
以上是兩種常用的添加數據的方法,你可以根據具體需求選擇適合的方法。