上下文
我想要一个列表,该列表具有3个明显不同的布局用于列表项,因此我根据要显示的项的类型来创建我的适配器,以创建适当的视图。
例如,我想列出一些图像,文本和数字,每个都有一些标题。我知道,
public View getView(int position, View convertView, ViewGroup parent)
在convertView
看台上重用不再可见listItems中的观点。
问题
如何选择convertView
或如何控制进入那里的物品?
问题来自于不同的listItems视图,假设我的列表以图像listItem开头,然后出现大量文本listItems和数字listItems,之后出现了100个listItems是第二个图像。我假设向下滚动列表,(在getView(...)
调用中)convertView
不为null的第一个是带有图像的列表,并且由于我需要显示文本listItem或数字listItem的视图,因此无法使用它。然后我想在每个下一次getView(...)
调用中,convertView
该图像列表项都与以前的调用中相同,因为我以前没有使用过它。
未使用的文本listItems和数字listItems卡住了,滚动列表时,我需要继续创建新视图,这就是我要防止的事情。
您需要让适配器的视图回收器知道不止一种布局,以及如何区分每一行的两种布局。只需覆盖以下方法:
我在这里说了2种不同的布局。如果您有更多使用枚举来区分它们。
@Override
public int getItemViewType(int position) {
// Define a way to determine which layout to use, here it's just evens and odds.
return position % 2;
}
@Override
public int getViewTypeCount() {
return 2; // Count of different layouts (Change according to your requirment)
}
将getItemViewType()合并到getView()中,如下所示:
if (convertView == null) {
// You can move this line into your constructor, the inflater service won't change.
mInflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
if(getItemViewType(position) == 0)
convertView = mInflater.inflate(R.layout.listview_item_product_1, parent,false);
else
convertView = mInflater.inflate(R.layout.listview_item_product_2,parent,false);
// etc, etc...
观看Android的Romain Guy在Google Talks上讨论视图回收器。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句