ListView汎用アダプタ


ListView汎用アダプタ
package org.adapter;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.cache.TransformUtils;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListViewAdapater extends BaseAdapter {

	protected List<?> data;

	protected int[] ids;

	protected Context context;

	protected LayoutInflater inflater;

	List<View> cacheViews = null;

	public ListViewAdapater(List<?> data, int resource, int[] ids, String[] keys,
			Context context) {
		this.data = data;
		this.ids = ids;
		this.context = context;
		inflater = LayoutInflater.from(this.context);
		cacheViews = new Vector<View>();
		int count = getCount();
		for (int position = 0; position < count; position++) {
			View view = inflater.inflate(resource, null);
			for (int x = 0; x < ids.length; x++) {
				int id = ids[x];
				View tempView = view.findViewById(id);
				if (tempView instanceof TextView) {
					TextView tv = (TextView) tempView;
					tv.setText(TransformUtils.toString(getValue(position,
							keys[x])));
				}
			}
		}
	}

	@Override
	public int getCount() {
		if (null == data) {
			return 0;
		}
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		return cacheViews.get(position);
	}

	public Object getValue(int position, String key) {
		Object obj = getItem(position);
		if (obj instanceof Map<?, ?>) {
			Map<?, ?> map = (Map<?, ?>) obj;
			return map.get(key);
		} else {
			try {
				Field field = obj.getClass().getDeclaredField(key);
				field.setAccessible(true);
				return field.get(obj);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}