Reputation: 51421
I have asked myself the above question and did not come to a real solution so far.
Below you can see two implementations of a custom adapter for a ListView
holding Strings
. The first implementation uses an additional list of values inside the Adapter
, like it is also done in many ListView
tutorials I have seen. (e.g. vogella-listview-tutorial)
public class CustomAdapter extends ArrayAdapter<String> {
private ArrayList<String> mList;
public CustomAdapter(Context context, List< String > objects) {
super(context, 0, objects);
mList = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
String item = mList.get(position);
// ... do stuff ...
return convertView;
}
}
The second implementation below simply uses the List
of Strings
that has already been handed to the Adapter
, and does not need an additional List. Instead, the Adapters
getItem(int pos)
method is used:
public class CustomAdapter extends ArrayAdapter<String> {
public CustomAdapter(Context context, List< String > objects) {
super(context, 0, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
String item = getItem(position);
// ... do stuff ...
return convertView;
}
}
Now my question:
What is the reason for using an additional List
inside a CustomAdapter
when you can simply use the adapters getItem(int pos)
method and spare the additional List
?
Upvotes: 0
Views: 61
Reputation: 157477
since you are extending ArrayAdapter
that extends BaseAdapter
you do not need to have a copy of the dataset, but providing it to the super
is enough. If you extends another adapter, BaseAdapter
you have to override
getCount()
getItem(int)
getView(int position, View convertView, ViewGroup parent)
getItemId(int)
all of the require to access to the dataset.
Upvotes: 1