Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate spinner with years dynamically in Android?

Tags:

I have been racking my brain trying to get this to work. I want to dynamically enter in years from 1900 to the current year into a spinner. I don't think that this is possible to do using an XML defined array but can I do it with an array adapter? Here is what I have so far:

ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);

for (int i = 1900; i <= thisYear; i++) 
{
    years.add(i);
}

adapter = new ArrayAdapter<String>(this, 
           android.R.layout.simple_spinner_item, years);

//spinner to enter this list to
spinYear = (Spinner)findViewById(R.id.yearspin);

Here's the XML for the spinner:

<Spinner
        android:id="@+id/yearspin"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

Thanks for any help.

like image 860
colmulhall Avatar asked Apr 10 '13 00:04

colmulhall


1 Answers

You're very close. Try this:

ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
for (int i = 1900; i <= thisYear; i++) {
    years.add(Integer.toString(i));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, years);

Spinner spinYear = (Spinner)findViewById(R.id.yearspin);
spinYear.setAdapter(adapter);

You just forgot to add

spinYear.setAdapter(adapter);
like image 185
vincentjames501 Avatar answered Sep 21 '22 15:09

vincentjames501