重写SimpleAdapter, 使它更而向对象。

前言
第一次用SimpleAdapter向LiveView加数据的时候,觉得使用List<Map>作为数据源怪怪的。
Google这样的设计也可以理解,因为使用Map的话,数据取值的时候确实比使用对象时更快,因为如果设计成自定义对象,取值时必定使用到反射,对移动设备来讲,使用反射的代价我想是比较高的。

另外好在Android是开源的,不然跟本无法重写这类对象,从而达到我们想要的效果。

下面我们使用反射机制来实现对自定义对象的支持。声明:本人绝对不会使用这种自定义对象的。因为反射的代价太大,这个重写只作研究之用。

下面代码与原SimpleAdapter不同的地方都使用了注释。

package hxf.Adapter;

import hxf.Tools.Reflect;

import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Checkable;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class ObjectSimpleAdapter<T> extends SimpleAdapter{
 
    private List<T> mData;{//把List<Map>转换成泛型
    private int[] mTo;
    private String[] mFrom;
    private ViewBinder mViewBinder;
    private final WeakHashMap<View, View[]> mHolders = new WeakHashMap<View, View[]>();
    private int mResource;
    private LayoutInflater mInflater;
    
public ObjectSimpleAdapter(Context context, ArrayList<T> data,
            int resource, String[] from, int[] to) {

 super(context, null, 0, null, null);//这个地方只传个context就好了,因为其他已经无用了。
        mData = data;
        mResource = resource;
        mFrom = from;
        mTo = to;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
 
@Override
 public int getCount() {//必须重写的方法(ListView会调用的),照抄原码
        return mData.size();
    }

 @Override
    public Object getItem(int position) {{//必须重写的方法,(ListView会调用的),照抄原码
        return mData.get(position);
    }
 
@Override
    public View getView(int position, View convertView, ViewGroup parent) {{{//必须重写的方法,照抄原码
        return createViewFromResource(position, convertView, parent, mResource);
    }

    private View createViewFromResource(int position, View convertView,
            ViewGroup parent, int resource) {{{//必须重写的方法,照抄原码,方法名可以随便写,只要getView调用就好了。
    
        View v = convertView;
        
        if (v == null) 
        {
            v = mInflater.inflate(resource, parent, false);

            final int[] to = mTo;
            final int count = to.length;
            final View[] holder = new View[count];

            for (int i = 0; i < count; i++)
                holder[i] = v.findViewById(to[i]);

            mHolders.put(v, holder);
        } 

        bindView(position, v);
        return v;
    }
 
private void bindView(int position, View view) {

        final Object dataSet = mData.get(position);
        if (dataSet == null)
            return;

        final ViewBinder binder = mViewBinder;
        final View[] holder = mHolders.get(view);
        final String[] from = mFrom;
        final int[] to = mTo;
        final int count = to.length;

        for (int i = 0; i < count; i++) {
            final View v = holder[i];
            if (v != null) {
            final Object data = Reflect.ref(dataSet, from[i]);//关键的地方,使用反射设置值
                String text = data == null ? "" : data.toString();
                if (text == null)
                    text = "";

                boolean bound = false;
                if (binder != null)
                    bound = binder.setViewValue(v, data, text);

                if (!bound) {
                    if (v instanceof Checkable)
                        if (data instanceof Boolean)
                            ((Checkable) v).setChecked((Boolean) data);
                        else 
                            throw new IllegalStateException(v.getClass().getName() +
                                    " should be bound to a Boolean, not a " + data.getClass());
                    else if (v instanceof TextView)
                        setViewText((TextView) v, text);
                    else if (v instanceof ImageView)
                        if (data instanceof Integer)
                        setViewImage((ImageView) v, (Integer) data);                            
                        else
                        setViewImage((ImageView) v, text);
                    else
                        throw new IllegalStateException(v.getClass().getName() + " is not a " +
                                " view that can be bounds by this SimpleAdapter");
                }
            }
        }
    }
 
}


//反射类。
public class Reflect {
	
	public static Object ref(Object obj, String fieldname)
	{
		try
		{
			String[] fieldarray = fieldname.split("\\.");
			
			if (fieldarray.length > 1)
				return getValue(obj, fieldname);
			
			int length = fieldarray.length;
			Object objtemp = obj;
			for(int i = 0; i < length; i++)
			{
				objtemp = getValue(objtemp, fieldarray[i]);
				
				if (i == length - 1 || objtemp == null)
					return objtemp;
			}
			
		}
		catch (Exception E)
		{
			System.out.println(E.getMessage());
		}
		
		return null;
	}
	
	@SuppressWarnings("unchecked")
	private static Object getValue(Object obj, String fieldname)
	{
		Class cls = obj.getClass();
		Object returnobj = null;
		
		try{
			Field field = cls.getField(fieldname);
			returnobj = field.get(obj);
		}catch (Exception E){}
		
		try{
			Method method = cls.getMethod(fieldname);
			returnobj = method.invoke(obj);
		}catch (Exception E){}
		
		return returnobj;
	}
}


欢迎大家加Q讨论:87648714

你可能感兴趣的:(java,android,SimpleAdapter)