ListView with ArrayAdapter and ViewHolder adding icons to the wrong item

后端 未结 3 814
陌清茗
陌清茗 2020-12-06 07:03

I have a dynamic ListView which uses an ArrayAdapter. When a name is selected from a spinner, the name together with an icon showing whether they a

3条回答
  •  醉酒成梦
    2020-12-06 07:34

    Update: ViewHolder is only meant to hold references to the component views inside the item layout. This helps to avoid the overhead of calling findViewById for rendering each component inside complex item layouts with multiple components(Like the TextView, and ImageView in this case).

    I fixed it by using a routine (called getSex) to retrieve the sex data and setting all the view data including icons outside the if-else blocks.

    The working code now looks like this:

    if (null == convertView) {
        Log.i("ANDY","Position not previously used, so inflating");
        convertView = inflater.inflate(R.layout.player_simple_list, null);
    
        // Creates a ViewHolder and store references to the two children views
        // we want to bind data to.
        holder = new ViewHolder();
        holder.text = (TextView) convertView.findViewById(R.id.label);
        holder.icon = (ImageView) convertView.findViewById(R.id.icon);
        convertView.setTag(holder);
    } else {
        // Get the ViewHolder back to get fast access to the TextView
        // and the ImageView.
        holder = (ViewHolder) convertView.getTag();
    }
    
    // Bind the data efficiently with the holder.
    holder.text.setText(getItem(position));
    // Change icon depending is the sexmale variable is true or false.
    if (getSex (getItem(position)) == true)  {
        holder.icon.setImageBitmap(maleicon);
    }
    else {
        holder.icon.setImageBitmap(femaleicon);
    }
    return convertView;
    

提交回复
热议问题