I’m using some reflection to set up a ListView made up of custom views. One of the HashMaps that I’ll be using with this Adapter has a button in it. I’m pretty sure I need to set the onClickListener on the button in the getView method, but I’m not sure how.
Here’s the code for my Adapter:
private class ViewAdapter extends BaseAdapter {
private HashMap<String, View> mMap = new HashMap<String, View>();
private String[] mKeys;
private Context mContext;
private ViewAdapter(Context context, HashMap<String, View> map) {
mContext = context;
mMap = map;
mKeys = mMap.keySet().toArray(new String[map.size()]);
}
@Override
public int getCount() {
return mMap.size();
}
@Override
public Object getItem(int position) {
return mKeys[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
Object myObject = null;
Class myViewClass = null;
Constructor constructor = null;
Method methodToExecute = null;
String[] arguments = {mKeys[position]};
try {
myViewClass = mMap.get(mKeys[position]).getClass();
//grab the constructor
constructor = mMap.get(mKeys[position]).getClass().getConstructor(Context.class);
//instantiate a new object.
myObject = (View) constructor.newInstance(getBaseContext());
//Grab the display method
methodToExecute = myViewClass.getMethod("display", new Class[] {String.class});
Log.i("method", methodToExecute.toString());
} catch (Exception e) {
e.printStackTrace();
}
if(convertView == null) {
row = (View) myObject;
} else {
row = convertView;
}
try {
methodToExecute.invoke(row, new Object[]{arguments});
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
}
EDIT – Yeah, this was a ridiculous design decision. I ended up scrapping the whole thing and just going for a regular ArrayList of some ADT I created which had a field of a Class that I could set to be my particular custom View class. You live and you learn 😉
I’m guessing here but in order to have a button, I would assume that the View is actually a ViewGroup. If so, try casting it to ViewGroup and iterating through the children Views using getChildAt(i):