在这里做了一个小demo,实现一个ListView中包含多种Item。
首先,建立一个继承自BaseAdapter的类,在里面重写如下方法。
1 获取ListView的Item个数 --->getCount()
@Override
public int getCount() {
// TODO Auto-generated method stub
return mData.size();
}
2 根据Item位置设置Item View Type ---->getItemViewType(int position)
@Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
if (getItem(position) instanceof String)
return 1;
else
return 0;
}
3 获取ListView中想要的Item类型个数 ---->getViewTypeCount()
@Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 2;
}
4 按Item位置获取当前Item的对象Object ---->getItem(int position)
@Override public Object getItem(int position) { // TODO Auto-generated method stub return mData.get(position); } 5 最后得修改非常重要的一个方法,该方法主要为了获得View ---->getView(int position, View convertView, ViewGroup parent)
@Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Log.e("position", "" + position); int nType = getItemViewType(position); if (nType == 1) convertView = mInflater.inflate(R.layout.list_item, null); else convertView = mInflater.inflate(R.layout.list_item2, null); return convertView; }
全部代码package com.example.testlist; import java.util.ArrayList; import android.app.Activity; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; public class NewAdapter extends BaseAdapter { private LayoutInflater mInflater; private ArrayList<Object> mData; public NewAdapter(Activity context) { mInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mData = new ArrayList<Object>(); } @Override public int getCount() { // TODO Auto-generated method stub return mData.size(); } @Override public int getItemViewType(int position) { // TODO Auto-generated method stub if (getItem(position) instanceof String) return 1; else return 0; } @Override public int getViewTypeCount() { // TODO Auto-generated method stub return 2; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return mData.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Log.e("position", "" + position); int nType = getItemViewType(position); if (nType == 1) convertView = mInflater.inflate(R.layout.list_item, null); else convertView = mInflater.inflate(R.layout.list_item2, null); return convertView; } public void addData(ArrayList<Object> data) { if (mData == null) { mData = data; return; } mData.addAll(data); } }