Adapter
import android.widget.BaseAdapter;
import java.util.List;
public abstract class CommonAdapter<T> extends BaseAdapter {
private List<T> mData;
public CommonAdapter(List<T> data) {
mData = data;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
}
代入泛型的抽象类,使用时需要重写
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return null;
}
使用样例
private List<Entity> data = new ArrayList<Entity>();
CommonAdapter<Entity> adapter = new CommonAdapter<Entity>(data) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(MainActivity.this)
.inflate(R.layout.item, parent, false);
}
//在这里设置item控件内容(与对应实体Entity相关)
return convertView;
}
};
ViewHolder
import android.graphics.Bitmap;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class ViewHolder {
@SuppressWarnings("unchecked")
public static <T extends View> T get(View view, int id) {
SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
if (viewHolder == null) {
viewHolder = new SparseArray<View>();
view.setTag(viewHolder);
}
View childView = viewHolder.get(id);
if (childView == null) {
childView = view.findViewById(id);
viewHolder.put(id, childView);
}
return (T) childView;
}
/**
* 设置TextView的文字
*
* @param view convertView
* @param id textView对应id
* @param text 文字
*/
public static void setTVText(View view, int id, String text) {
TextView tv = get(view, id);
tv.setText(text);
}
/**
* 设置ImageView的图片
*
* @param view convertView
* @param id ImageView对应id
* @param drawableId 图片id
*/
public static void setImageDrawable(View view, int id, int drawableId) {
ImageView imageView = get(view, id);
imageView.setImageResource(drawableId);
}
/**
* 设置ImageView的图片
*
* @param view convertView
* @param id ImageView对应id
* @param bm bitmap
*/
public static void setImageBitmap(View view, int id, Bitmap bm) {
ImageView imageView = get(view, id);
imageView.setImageBitmap(bm);
}
}
使用需要配合Adapter
配合通用Adapter的样例
CommonAdapter<Entity> adapter = new CommonAdapter<Entity>(data) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(MainActivity.this)
.inflate(R.layout.item, parent, false);
}
//普通获取控件(可能需要强转)
View v = ViewHolder.get(convertView,R.id.view);
//仅设置显示内容(图片/文字)
ViewHolder.setTVText(convertView, R.id.tv1, data.get(position)
.getName());
ViewHolder.setImageDrawable(convertView, R.id.iv,
data.get(position).getIcon());
return convertView;
}
};
进行项目开发时,可以用这2个固定类完成大部分ListView、Gridview的Adapter与ViewHolder的实现,简化代码。