Skip to content

Instantly share code, notes, and snippets.

@rivancic
Created March 6, 2016 15:37
Show Gist options
  • Save rivancic/0fe73159d7a2a236985d to your computer and use it in GitHub Desktop.
Save rivancic/0fe73159d7a2a236985d to your computer and use it in GitHub Desktop.
Stub class for Android view Adapter
package com.rivancic.adapters;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import com.rivancic.adapters.R;
public class ListAdapter extends ArrayAdapter<Item> {
/**
* It helps with formatting data for UI.
*/
public ListAdapter(Activity context, List<Item> items) {
// This is an ugly hack to use the simpler to intatntiate ArrayAdapter instead of
// BaseAdapter. The problem is second parameter that specifies id of textview for item
// layout which is overidden in the getView method. ¯\_(ツ)_/¯
super(context, 0, items);
}
/**
* Display the Itemdata of the specific position in the row of a list view.
*
* @param position position of a Item in the list that is shown.
* @param convertView View that can be reused.
* @param parent in parameter.
*
* @return the filled row view with data.
*/
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = convertView;
final ViewHolder viewHolder;
if (rowView == null) {
// Inflate new view.
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.list_item, parent, false);
// Init ViewHolder and set it to the rovView.
viewHolder = new ViewHolder(rowView);
rowView.setTag(viewHolder);
} else {
// Get the view elements from the ViewHolder saved in rovView.
viewHolder = (ViewHolder) rowView.getTag();
}
final Item item = getItem(position);
if (viewHolder.title != null) {
viewHolder.title.setText(item.getTitle());
}
return rowView;
}
/**
* Holder for the Item row.
* So there is no need to searching for views next time we are accessing the existing riwView.
*/
static class ViewHolder {
private TextView title;
public ViewHolder(View rowView) {
title = (TextView) rowView.findViewById(R.id.title);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment