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

后端 未结 2 2281
耶瑟儿~
耶瑟儿~ 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;
    }
    
    0 讨论(0)
  • 2021-02-15 19:57

    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.

    0 讨论(0)
提交回复
热议问题