How to add a dynamic view to a ListView item at runtime?

后端 未结 3 751
Happy的楠姐
Happy的楠姐 2021-01-02 14:58

My problem is that I don\'t know whether I should use multiple list view or a custom listview item adapter which can grows dynamically. For example, for a particular user, t

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-02 15:20

    Here's an idea that'll probably enable you to introduce as many item types as you like without having to modify adapter every time you do:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        AbstractItem abstractItem = ((AbstractItem)getItem(position));
        // if null or new item type is different than the one already there
        if (convertView == null || (convertView.getTag() != null
                && ((AbstractItem)convertView.getTag()).getType().equals(abstractItem.getType())) {
              convertView = abstractItem.inflateSelf(getContext());
        }
    
        abstractItem.fillViewWithData(convertView);
        convertView.setTag(abstractItem);
        return convertView;
    }
    
    public class AbstractItem {
        public abstract View inflateSelf(Context context);
        public abstract String getType();
        public abstract void fillViewWithData(View view);
    }
    
    public class PictureSnapItem extends AbstractItem {
        // data fields
        WeakReference wBitmap;
        String pictureComment;
        ...
    
        public abstract View inflateSelf(Context context) {
            // get layout inflater, inflate a layout resource, return
            return ((Activity)context).getLayoutInflater.inflate(R.layout.picture_snap_item);
        }
        public abstract String getType() {
            // return something class-specific, like this
            return getClass().getCanonicalName();
        }
        public abstract void fillViewWithData(View view) {
            // fill the view with data from fields, assuming view has been
            // inflated by this very class's inflateSelf(), maybe throw exception if
            // required views can't be found
            ImageView img = (ImageView) view.findViewById(R.id.picture);
            TextView comment = (TextView) view.findViewById(R.id.picture_comment)
        }
    }
    

    ... and then extend AbstractItem and add instances to adapter, no need to add any if clauses to getView() any more.

提交回复
热议问题