在Android中,可以使用以下方法向ListView添加行:
ListView listView = findViewById(R.id.list_view);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
adapter.add("行1");
adapter.add("行2");
adapter.add("行3");
listView.setAdapter(adapter);
ListView listView = findViewById(R.id.list_view);
List<Map<String, Object>> data = new ArrayList<>();
Map<String, Object> row1 = new HashMap<>();
row1.put("text", "行1");
data.add(row1);
Map<String, Object> row2 = new HashMap<>();
row2.put("text", "行2");
data.add(row2);
Map<String, Object> row3 = new HashMap<>();
row3.put("text", "行3");
data.add(row3);
SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_1, new String[]{"text"}, new int[]{android.R.id.text1});
listView.setAdapter(adapter);
ListView listView = findViewById(R.id.list_view);
CustomAdapter adapter = new CustomAdapter();
listView.setAdapter(adapter);
...
private class CustomAdapter extends BaseAdapter {
private String[] data = {"行1", "行2", "行3"};
@Override
public int getCount() {
return data.length;
}
@Override
public Object getItem(int position) {
return data[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(android.R.layout.simple_list_item_1, parent, false);
}
TextView textView = convertView.findViewById(android.R.id.text1);
textView.setText(data[position]);
return convertView;
}
}
以上是常见的向ListView添加行的方法,可以根据实际需求选择适合的方法。