2

I have a listview that contains a bunch of spinners, but when I scroll the listview, the value for the spinner is reset. Is there a way to fix this? This is what my ArrayAdapter class looks like.

public class ProductArrayAdapter extends ArrayAdapter { private final Context context;

private final List<Product> values;

public ProductArrayAdapter( Context context, List<Product> values ) {
  super( context, R.layout.product_item, values );
  this.context = context;
  this.values = values;
}

@Override
public View getView( int position, View convertView, ViewGroup parent ) {
  LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
  View rowView = inflater.inflate( R.layout.product_item, parent, false );
  Product availableProduct = values.get( position );

  ((TextView) rowView.findViewById( R.id.productCode )).setText( Product.getProductName( availableProduct.getProductCode( ) ) );

  ((Spinner) rowView.findViewById( R.id.count )).setAdapter( productCounts );

  return rowView;
}

}

labatyo
  • 486
  • 8
  • 17
  • Whenever you scroll, you're inflating every list item, so you're losing all the old values. You need to reset it in getView each time. – Gabe Sechan Feb 25 '13 at 17:12
  • ListViews (and other AdapterViews) recycle the layout in each row, so you need to save the values in another location. Please watch [Turbo-Charge Your UI](http://www.google.com/events/io/2009/sessions/TurboChargeUiAndroidFast.html) or [World of ListView](http://www.google.com/events/io/2010/sessions/world-of-listview-android.html) by Android's lead developers, they cover this topic in great detail. – Sam Feb 25 '13 at 17:13

2 Answers2

6

I was able to get it working, but since no one answered my question, I'll just post the solution myself.

I created a HashMap<Integer,Integer> called selectedItems to store the values of the ArrayAdapter, and set them in the onItemSelected listener. And set the current selected item of the Spinner based on the HashMap.

      if ( selectedItems.get( position ) != null ) {
    ((Spinner) rowView.findViewById( R.id.count )).setSelection( selectedItems.get( position ) );
  }

  ((Spinner) rowView.findViewById( R.id.count )).setOnItemSelectedListener( new OnItemSelectedListener( ) {

    public void onItemSelected( AdapterView<?> parent, View view,
        int pos, long id ) {
      selectedItems.put( position, pos );
    }

Hopefully this is helpful to anyone else with the same problem in the future

labatyo
  • 486
  • 8
  • 17
0

Just in case it helps anyone, I was having the same problem with a listView that had one editText and one spinner, and I had the issue with both of those views. As soon as I fixed the problem with the editText by using onFocusChangeListener rather than onTextChangeListener (see solution here - see the one from defpillz), the issue with the spinner disappeared.

Community
  • 1
  • 1
PrincessLilly
  • 415
  • 1
  • 8
  • 21