其他分享
首页 > 其他分享> > Android BaseAdapter:在getView()重新输入时convertView null

Android BaseAdapter:在getView()重新输入时convertView null

作者:互联网

我正在根据http://bartinger.at/listview-with-sectionsseparators/中描述的技术构建具有部分的ListView.但是我想通过重用convertView来扩展它来扩展它.但是,我发现每次输入getView()方法时convertView变量为null.有人可以解释为什么会这样吗?

ViewHolder holder;
final ListViewItem item = items.get(position);

if (item.isSection()) {
    Section section = (Section)item;

    convertView = inflater.inflate(R.layout.section, null);
    TextView title = (TextView) convertView.findViewById(R.id.section_title);
    title.setText(section.title);
} else {
    if (convertView == null) {
        Log.d("Adapter", "convertView was null");
    }

    Server server = (Server)item;

    convertView = inflater.inflate(R.layout.server_row, null);
    holder = new ViewHolder();
    holder.serverName = (TextView) convertView.findViewById(R.id.server_name);
    holder.serverStatusIcon = (ImageView)convertView.findViewById(R.id.server_status_icon);
    convertView.setTag(holder);

    holder.serverName.setText(server.name);
}

return convertView;

正在创建和显示列表而没有错误,并且包含部分和非部分项目就好了.

解决方法:

你正确实施吗

getItemViewType (int position) ?

从Android的文档中看到:

Returns

An integer representing the type of View. Two views should share the same type if one can be converted to the other in getView(int, View, ViewGroup). Note: Integers must be in the range 0 to getViewTypeCount() – 1. IGNORE_ITEM_VIEW_TYPE can also be returned.

所以也许convertView总是为null,因为适配器不知道哪些项属于一起,所以它不知道哪些项被传递回来…

试试这个:

@Override
public int getItemViewType(int position) {
    if (((MyItem)getItem(position)).isHeader()) {
        return 1;
    } else {
        return 0;
    }
}

@Override
public int getViewTypeCount() {
    return 2;
}

您在getItemViewType中返回的索引只是将标题和非标题组合在一起的标识符.

在这种情况下,您必须在模型项中实现方法“isHeader”(或类似).

标签:android,baseadapter,convertview
来源: https://codeday.me/bug/20190902/1787962.html