Android --- BaseAdapter

BaseAdapter就Android应用程序中经常用到的基础数据适配器,它的主要用途是将一组数据传到像ListView、Spinner、Gallery及GridView等UI显示组件,它是继承自接口类Adapter。

class MyAdapter extends BaseAdapter {

	private LayoutInflater mInflater;

	private List> listData;// 存放 Title + item
	private List> splitData; // 存放Title

	public MyAdapter(Context context, List> listData,
			List> splitData) {
		this.mInflater = LayoutInflater.from(context);
		this.listData = listData;
		this.splitData = splitData;
	}

	public int getCount() {
		return listData.size();
	}

	public Object getItem(int position) {
		return listData.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	/** 是否是个分隔item */
	public boolean isEnabled(int position) {
		if (splitData.contains(listData.get(position))) {
			return false;
		}
		return super.isEnabled(position);
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		if (splitData.contains(listData.get(position))) {
			//如果数据里的内容包含Title信息的,就是Title信息了---- 用“list_items_tag”布局
			convertView = mInflater.inflate(R.layout.list_items_tag, null);
		} else {
			//如果数据里的内容没包含Title ---- 用“list_items”布局
			convertView = mInflater.inflate(R.layout.list_items, null);
		}

		TextView textView = (TextView) convertView.findViewById(R.id.itemTitle);
		textView.setText(listData.get(position).get("itemTitle"));

		return convertView;
	}

}


public class MyListView5 extends Activity {
	// 存放( Title + item)
	private List> mylist = new ArrayList>();
	// 存放Title
	private List> splitList = new ArrayList>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.groupview);

		ListView lv = (ListView) findViewById(R.id.MyListView);

		setData(); // 设置数据

		// 配置适配器
		MyAdapter adapter = new MyAdapter(this, mylist, splitList); // 布局里的控件id
		// 添加并且显示
		lv.setAdapter(adapter);

	}

	private void setData() {
		// 组织数据源
		Map mp = new HashMap();
		mp.put("itemTitle", "A");
		mylist.add(mp);// 存放( Title + item)
		splitList.add(mp);// 存放Title

		for (int i = 0; i < 3; i++) {
			Map map = new HashMap();
			map.put("itemTitle", "文章1-" + i);
			mylist.add(map);// 存放( Title + item)
		}
		mp = new HashMap();
		mp.put("itemTitle", "B");
		mylist.add(mp);// 存放( Title + item)
		splitList.add(mp);// 存放Title

		for (int i = 0; i < 6; i++) {
			Map map = new HashMap();
			map.put("itemTitle", "文章2-" + i);
			mylist.add(map);// 存放( Title + item)
		}
	}
}


你可能感兴趣的:(Android)