首页 > 代码库 > android 通用适配器

android 通用适配器

每次创建一个集合,都要创建 一个适配器,每次每次都因为数据的结构不一样而创建一个视图。

这里我创建了一个适配器,不管数据什么结构,都能使用该适配器进行数据装载。

package org.adapter;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Vector;

import org.asynctask.AsyncTaskManager;
import org.asynctask.ShowImgaeLater;
import org.tourists.R;
import org.utils.StringUtils;
import org.utils.TransformUtils;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class DataAdapter extends BaseAdapter {
	
	protected String[] keys ; 
	
	protected int[]resIds;
	
	protected Activity context ; 
	
	protected int layout ; 
	
	protected LayoutInflater layoutInflater ; 
	
	public List<?> datas ;  
	
	public DataAdapter( Activity context, List<?> datas,String[] keys, int[] resIds, 
			int layout) {
		this.keys = keys;
		this.resIds = resIds;
		this.context = context;
		this.layout = layout;
		this.layoutInflater = LayoutInflater.from(context);
		this.datas = datas;
	}

	@Override
	public int getCount() {
		return datas.size() ;
	}

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

	@Override
	public long getItemId(int position) {
		return toInt(invoke(getItem(position), "id") ); 
	} 

	@Override
	public View getView(int position, View convertView, ViewGroup parent){
		if(null == convertView){
			convertView = layoutInflater.inflate(layout, null ) ; 
		}else{
			int upPostion = TransformUtils.toInt( convertView.getTag() ) ;
			if( upPostion == position){
				return convertView ; 
			}
		}
		Object target = getItem( position ) ; 
		for(int x=0;x<resIds.length;x++){
			View view = convertView.findViewById(resIds[x]); 
			String key = keys[x] ;
			String value = http://www.mamicode.com/invoke(target, key) ; >
</pre></p><p></p>该适配器调用方法如下:<pre name="code" class="java">ListView lv_scenic_show = (ListView) findViewById( R.id.lv_scenic_show ) ;  
		
		lv_scenic_show.setAdapter( new DataAdapter(this, points,
				new String[]{"cover" , "pictureCount" , "audioCount" , "distance" , "sname" }
			, new int[]{R.id.iv_scenic_item_main , R.id.tv_scenic_pic ,R.id.tv_scenic_mp3 , 
				R.id.tv_scenic_distance , R.id.tv_scenic_panorama_scenics_name }
		, R.layout.scenic_panorama_item ) ) ;  



android 通用适配器