前段时间,看到覆盖Adapter的两个函数(如下):
private static final int VIEW_TYPE_NULL = 0;
private static final int VIEW_TYPE_CITY = 1;
private static final int VIEW_TYPE = 2;
@Override
public int getViewTypeCount() {
return VIEW_TYPE;
}
@Override
public int getItemViewType(int position) {
CityObj c = (CityObj) mAllTheCitiesList[position];
if (c.mCityId == null) {
return VIEW_TYPE_NULL;
} else {
return VIEW_TYPE_CITY;
}
}
getViewTypeCount()和getItemViewType(int position)用来干什么的呢?先看一下用到这两个函数的一个ListView的效果图:
这个效果图片里面就是只有这个ListView,请注意其中有两个不同的菜单项:。也就是说这个ListView里面有两个不同菜单项(不同的view)。我们知道其实每一个菜单项其实是在这个函数getView(int position, View view, ViewGroup parent) 里面初始化的(加载的)。那么这个地方的ListView的不同菜单项也是在这个函数里面去定义的。先说到这里。
我们来看看getViewTypeCount()这个函数google是怎么解释的(如下):
Returns the number of types of Views that will be created by {@link #getView}. Each type represents a set of views that can be converted in {@link #getView}. If the adapter always returns the same type of View for all items, this method should return 1.
其主要意思是:这个函数是用来告知在当前这个Adapter的getView函数里加载的不同view的数量,如果每一个view都相同,则其返回值为1.
再来看看getItemViewType(int position)的解释:
Get the type of View that will be created by {@link #getView} for the specified item. 获取这个给定的菜单项的类型(由于每个菜单项可能不同,所以每一个菜单项就有可能是不同的类型)。
An integer representing the type of View. 用一个整数来标示不同view的类型。
看了上面的叙述,应该是明白getViewTypeCount()和getItemViewType()的含义了吧!我们来看看
public View getView(int position, View view, ViewGroup parent) {
if (mAllTheCitiesList == null || position < 0 || position >= mAllTheCitiesList.length) {
return null;
}
CityObj c = (CityObj)mAllTheCitiesList [position];
// Header view (A CityObj with nothing but the first letter as the name
if (c.mCityId == null) {
if (view == null || view.findViewById(R.id.header) == null) {
view = mInflater.inflate(R.layout.city_list_header, parent, false);
}
TextView header = (TextView)view.findViewById(R.id.header);
header.setText(c.mCityName);
} else { // City view
// Make sure to recycle a City view only
if (view == null || view.findViewById(R.id.city_name) == null) {
view = mInflater.inflate(R.layout.city_list_item, parent, false);
}
view.setOnClickListener(CitiesActivity.this);
TextView name = (TextView)view.findViewById(R.id.city_name);
TextView tz = (TextView)view.findViewById(R.id.city_time);
CheckBox cb = (CheckBox)view.findViewById(R.id.city_onoff);
cb.setTag(c);
cb.setChecked(mSelectedCitiesList.containsKey(c.mCityId));
cb.setOnCheckedChangeListener(CitiesActivity.this);
mCalendar.setTimeZone(TimeZone.getTimeZone(c.mTimeZone));
tz.setText(DateFormat.format(mIs24HoursMode ? "k:mm" : "h:mmaa", mCalendar));
name.setText(c.mCityName);
}
return view;
}