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

前端 未结 6 958
长情又很酷
长情又很酷 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:26

    When your event is triggered you should just call a notifyDataSetChanged on your adapter so that it will call again getView for all your visible elements.

    Your getView method should take into account that some elements may have different background colors (and not forget to set it to normal color if the element doesn't need the changed background, else with recycling you would have many elements with changed background when you scroll)

    edit :

    I would try something like this :

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null)
        {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.card, parent, false);
        }
    
        //This part should also be optimised with a ViewHolder
        //because findViewById is a costly operation, but that's not the point of this example
        CardView cardView =(CardView)convertView .findViewById(R.id.card);
    
        //I suppose your card should be determined by your adapter, not a new one each time
        Card card = getItem(position);
    
        //here you should check sthg like the position presence in a map or a special state of your card object
        if(mapCardWithSpecialBackground.contains(position))
        {
            card.setBackgroundResource(specialBackground);
        }
        else
        {
            card.setBackgroundResource(normalBackground);
        }
        cardView.setCard(card);
    
        return convertView;
    }
    

    And on the special event i would add the position of the item into the map and call notifyDataSetChanged.

提交回复
热议问题