11

When normally populating a Spinner as I have done in the past I normally use a SpinnerAdapter then normally have items in resources to populate it.

I have currently though a different query, I have in my code a user input for an int and I want my spinner to populate with numbers up to the user selected number. So if the user enters the number '5' it is saved to an int variable. I then want the Spinner to show 1,2,3,4,5 as choices.

I am really not sure how I would approach this.

Thanks, Oli

Oli Black
  • 441
  • 2
  • 9
  • 23
  • http://stackoverflow.com/questions/5999262/populate-spinner-dynamically-in-android-from-edit-text Use an adapter.. – Tim Malseed Jan 09 '13 at 01:50

1 Answers1

31

Edited

Below is a basic example of how you would add Integers to your spinner :

mspin=(Spinner) findViewById(R.id.spinner1);
Integer[] items = new Integer[]{1,2,3,4};
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,android.R.layout.simple_spinner_item, items);
mspin.setAdapter(adapter);

You can refer to this and make changes in your project as per your logic. Also in your case you should use an ArrayList of integers since the number of choice of the user seems to be dynamic. you can create an arraylist and replace in for the Integer array in the above code.

Hope this helps!!

Bart Burg
  • 4,786
  • 7
  • 52
  • 87
Abhishek Sabbarwal
  • 3,758
  • 1
  • 26
  • 41
  • If you don't know the maximum number at compile time, you can create the `items` array at run-time (e.g. `Integer[] items = new Integer[size];` and a for loop to populate the array). In this case, it might be easier to use a `List` and `ListAdapter`. – Code-Apprentice Jan 09 '13 at 02:17
  • I just gave the example and then realized that the input is dynamic. Just edited my answer. An ArrayList of integers would suffice in his case. – Abhishek Sabbarwal Jan 09 '13 at 02:19
  • Your answer has the right general idea. I just wanted to expand on it and didn't feel like posting an answer of my own. ;-) – Code-Apprentice Jan 09 '13 at 02:21
  • I totally agree with you :) I was too quick to answer here. But immediately realized that it had to be edited. – Abhishek Sabbarwal Jan 09 '13 at 02:22
  • You have to add at the end mspin.setAdapter(adapter); – Chris Sim Jul 25 '13 at 12:51