I have seen the model created in this question: A generic MVC ArrayAdapter class
This is the adapter class:
public class MVCArrayAdapter<ModelType> extends BaseAdapter{
Activity ctx;
ArrayList<ModelType> array = new ArrayList<ModelType>();
Constructor<?> viewConstructor;
public MVCArrayAdapter(Activity context, String viewClassName) throws NoSuchMethodException, ClassNotFoundException {
super();
ctx = context;
viewConstructor = Class.forName(viewClassName).getConstructor(Activity.class);
}
public int getCount() {
return array.size();
}
public Object getItem(int position) {
return array.get(position);
}
public long getItemId(int position) {
return position;
}
@SuppressWarnings("unchecked")
public View getView(int position, View convertView, ViewGroup parent) {
ListViewRow<ModelType> view = (ListViewRow<ModelType>)convertView;
if (view == null) {
try {
view = (ListViewRow<ModelType>)viewConstructor.newInstance(ctx);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
view.setModel((ModelType)getItem(position));
return view;
}
public void add(ModelType object){
array.add(object);
}
public void addAll(Collection<? extends ModelType> objects){
array.addAll(objects);
}
public void addAll(ModelType... objects){
for(ModelType object : objects){
array.add(object);
}
}
public void clear(){
array.clear();
}
public void insert(ModelType object, int index){
array.set(index, object);
}
public void remove(ModelType object){
array.remove(object);
}
public void sort(Comparator<? super ModelType> comparator){
Collections.sort(array, comparator);
}}
And the row view class:
public abstract class ListViewRow<ModelType> extends FrameLayout {
ModelType model;
View childView;
public ListViewRow(Activity context, int viewLayout) {
super(context);
LayoutInflater inflater = context.getLayoutInflater( );
childView = inflater.inflate( viewLayout, this, false );
addView(childView);
}
public abstract void setModel(ModelType newModel);}
Here's an example child view class that sets a text field and a image field, to show the amount of work in creating the row view:
public class AdapterRow extends ListViewRow<String> {
TextView tv;
ImageView iv;
public AdapterRow(Activity context) {
super(context, R.layout.li);
tv = (TextView)findViewById(R.id.tv);
iv = (ImageView)findViewById(R.id.iv);
}
public void setModel(String str){
tv.setText(str);
iv.setImageResource(R.drawable.ic_launcher);
}}
the code is good but i was trying to add a holder and didn't where should i do this ?