Different row layouts in ListView

后端 未结 2 1171
自闭症患者
自闭症患者 2020-12-01 14:55

This post is related to this ViewHolder not working. On that post, I was following a tutorial on how to use ViewHolder on a ListView. What I want

2条回答
  •  星月不相逢
    2020-12-01 15:37

    The problem is that once you've inflated the view it can be reused many times in any position. I'd suggest the following approach: you inflate all but last item as usual (including the view holder), but for the last item you hold the reference as a field of CustomListAdapter and return it every time the last item is requested:

    private class CustomListAdapter extends ArrayAdapter { 
        ...
        private View mLastItem; 
    
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = convertView;
            ...
            int lastpos = mList.size()-1;
    
            if (view == null) {
                ViewHolder holder = new ViewHolder();
                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
                if (position == lastpos) {
                    view = vi.inflate(R.layout.list_item_record, null);
                    holder.textView = (TextView)view.findViewById(R.id.record_view);
                    mLastItem = view;
                }
                else {
                    view = vi.inflate(R.layout.list_item_bn, null);
                    holder.textView = (TextView)view.findViewById(R.id.tv_name);
                }
                view.setTag(holder);
            }
    
            if (position == lastpos) {
                ... // Update the last item here
                return mLastItem; 
            }
            ...
        }
    
    }
    

提交回复
热议问题