ListView: how to access Item's elements programmatically from outside?

前端 未结 6 1014
长情又很酷
长情又很酷 2021-01-22 02:17

I have the following situation.

I have a ListView, each item of the ListView is comprised of different widgets (TextViews, ImageViews, etc...) inflated form a Layout in

6条回答
  •  爱一瞬间的悲伤
    2021-01-22 02:34

    What I normally do is this:

    public static class EventDetailsRenderer {
    
        private TextView title;
    
        private TextView description;
    
        private Event item;
    
        public EventDetailsRenderer(View view) {
            extractFromView(view);
        }
    
        private final void extractFromView(View view) {
            title = (TextView) view.findViewById(R.id.EventTitle);
            description = (TextView) view.findViewById(R.id.Description);
        }
    
        public final void render() {
                render(item);
        }
    
        public final void render(Event item) {
            this.item= item;
            title.setText(item.getTitle());
            description.setText(item.getDescription());
        }
    }
    
    private class EventsAdapter
            extends ArrayAdapter {
    
        public EventsAdapter(Context context) {
            super(context, R.layout.list_node__event_details, 0);
        }
    
        public void addAllItems(Event... services) {
            for (int i = 0; i < services.length; i++) {
                add(services[i]);
            }
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Event event = getItem(position);
            EventDetailsRenderer eventRenderer;
    
            if (convertView != null && convertView.getTag() != null) {
                eventRenderer = (EventDetailsRenderer) convertView.getTag();
            } else {
                convertView = getActivity().getLayoutInflater().inflate(R.layout.list_node__event_details, null);
                eventRenderer = new EventDetailsRenderer(convertView);
                convertView.setTag(eventRenderer);
            }
    
            eventRenderer.render(event);
            return convertView;
        }
    }
    

    NOTE: that this example might not compile I pasted it from some code I have and deleted some lines to show an example but the logic it the same.

    And then when you want to render it, just get the children from the list, iterate over them, check if the renderer contains the card you want to flip and call its render method... then you render a specific item in the list without effecting the rest of the items.

    Let me know if this works...

    Adam.

提交回复
热议问题