Why is Android recycling the wrong view type in my SpinnerAdapter?

做~自己de王妃 提交于 2019-12-03 12:44:04

As David found out, this is related to the Android framework. As noted here, the framework doesn't expect Spinners to have different view types.

This is the workaround I used to make my SpinnerAdapter work as I wanted:

  • store the view type in the view's tag;
  • inflate a new layout if there is no view to convert OR if the current view type differs from the view to convert from.

Here's the code of my custom getView method:

private View getView(final int layoutResId, final int position, final View convertView, final ViewGroup parent) {
    View v;

    if (convertView == null || (Integer)convertView.getTag() != getItemViewType(position)) {
        final LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = li.inflate(layoutResId, parent, false);
    } else {
        v = convertView;
    }

    v.setTag(Integer.valueOf(getItemViewType(position)));

    final TextView tv = (TextView) v.findViewById(mTextViewResId);
    if (tv != null) {
        tv.setText(getText(position));

        if (isSeparator(position)) {
            tv.setOnClickListener(null);
            tv.setOnTouchListener(null);
        }
    }

    return v;
}

The problem is here:

public View getView(final int position, final View convertView, final ViewGroup parent) {
    return getView(mActionBarItemLayoutResId, position, convertView, parent);
}

This method will always return the same View type, whether called for a separator or a data item. You need to check the position here and return an appropriate view.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!