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

后端 未结 2 2282
耶瑟儿~
耶瑟儿~ 2021-02-15 19:46

I\'m trying to make an ActionBar spinner that has separators. I have implemented a SpinnerAdapter that has 2 item view types (thanks to getViewTypeCount

2条回答
  •  爱一瞬间的悲伤
    2021-02-15 19:56

    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;
    }
    

提交回复
热议问题