android開發在adapter中使用反射添加元素

    android開發中最經常使用的控件之一就是listview,伴隨listview還要有adapter和放入適配器的item.而後假設其中有一部分item的生成符合必定規律,Item item = new Item(jsonObject);那麼就該考慮下用反射來生成這些元素了.java

首先是item的代碼android

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對象的代碼json

Object object = TestItem.class.getConstructors()[0].newInstance(json);

放入adapter以後就是ide

/**
 * 適配器的抽象類
 * 
 * @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的類和佈局文件就能夠了佈局

例如this

 

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;
	}
};
相關文章
相關標籤/搜索