The adapter class can add another layer of abstraction and complexity, but when used correctly, it can greatly improve the performance of your app.
Basics
We use the adpater class to set up pagination when displaying a list view. The adapter achieves this by sitting between our data and view.
When scrolling a list of items from the ListView, any items that you scroll out of are sent to a part of the ListView
called the Recycler. The Recycler allows the Adapter to take over our now unused view using convertView()
, and return that view instead of creating a new one.
Lets take a look at what getView()
would look like to achieve something like this.
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item, null);
}
((TextView) convertView.findViewById(R.id.text)).setText(DATA[postion]);
((ImageView) convertView.findViewById(R.id.icon)).setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
}
Our code takes a view named convertView
, and if it has not been inflated yet, it will do so in the first code block. This will continue until your current view is full.