What is the method for adding rows in a ListView?
In Android, you can add items to a ListView using the following methods:
- You can utilize the ArrayAdapter to create an ArrayAdapter object, adding data one by one using the add() method, and then set the adapter to the 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);
- You can use a SimpleAdapter to create an object and store each row’s data in a List
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);
- Custom Adapter: You can create a custom Adapter class that extends BaseAdapter and override the getView() method to define the view for each row, then set the custom Adapter to the ListView.
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;
}
}
These are the common methods for adding rows to a ListView, you can choose the appropriate one depending on your actual needs.