android开发在adapter中使用反射添加元素
android开发中最常用的控件之一就是listview,伴随listview还要有adapter和放入适配器的item.然后假设其中有一部分item的生成符合一定规律,Item item = new Item(jsonObject);那么就该考虑下用反射来生成这些元素了.
首先是item的代码
public class TestItem { public int id; public String image; public TestItem(JSONObject json) { try { id = json.getInt("id"); } catch (JSONException e1) { e1.printStackTrace(); } try { image = json.getString("image"); } catch (JSONException e) { e.printStackTrace(); } } }
然后是生成一个item对象的代码
Object object = TestItem.class.getConstructors()[0].newInstance(json);
放入adapter之后就是
/** * 适配器的抽象类 * * @author oldfeel */ public abstract class BaseBaseAdapter extends BaseAdapter { private List<Object> list = new LinkedList<Object>(); /** 适配器中元素的类 */ private Class<?> classItem; /** * * @param context * @param classItem * 适配器中元素的类 */ public BaseBaseAdapter(Class<?> classItem) { this.classItem = classItem; } /** * 预处理清除列表数据和获取jsonarray * * @param page * 页码 * @param json * json对象 * @throws JSONException */ public void putJSON(JSONObject json, int page) { if (page == 1) { list.clear(); } try { JSONArray array = json.getJSONArray("adimage"); for (int i = 0; i < array.length(); i++) { try { Object object = classItem.getConstructors()[0] .newInstance(array.getJSONObject(i)); addItem(object); } catch (Exception e) { e.printStackTrace(); } } } catch (JSONException e1) { e1.printStackTrace(); } } /** * 清除list */ public void clear() { list.clear(); notifyDataSetChanged(); } /** * 添加元素 * * @param object */ public void addItem(Object object) { list.add(object); notifyDataSetChanged(); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { if (position > list.size() - 1) { return null; } return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { return getExView(position, convertView, parent); } public abstract View getExView(int position, View convertView, ViewGroup parent); }
在使用adapter的时候继承BaseBaseAdapter并输入item的类和布局文件就可以了
例如
BaseBaseAdapter adapter = new BaseBaseAdapter( TestItem.class) { @Override public View getExView(int position, View convertView, ViewGroup parent) { TestItem item = (TestItem) getItem(position); TextView textView = new TextView(MainActivity.this); textView.setText(item.image); return textView; } };