码迷,mamicode.com
首页 > 其他好文 > 详细

ListView通用适配器

时间:2014-12-23 10:29:02      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:android   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;
	}
}


ListView通用适配器

标签:android   listview   适配器   

原文地址:http://blog.csdn.net/hfmbook/article/details/42099359

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!