How to let user choose a specific year from a spinner

时间:2016-10-20 12:43:26

标签: android android-spinner android-datepicker

Hello I want the user to be able to click a spinner and choose a year from those I provide. I would provide a range from 1970 to current year, but I don't know how to implement it.

If I create a spinner and give it an array like this

<string-array name="spinnerItems">
    <item>1970</item>
    <item>1971</item>
</string-array>

Then I would need to add more than 40 items by hand, and I would need to update the app manually every year. Also the spinner onClick callback returns not the string value but the index of the string in the array, so for example 1972 would be index 3.

Also I will provide another spinner where the user will choose a year that's greater or equal of the year choosen in the first spinner.

In the end I want tos end an api request with an interval of years.

How can I do this?

2 个答案:

答案 0 :(得分:2)

I think you have to create year picker instead of creating number list of spinner

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);

Hope this will help..

答案 1 :(得分:0)

You can add items to a spinner programmatically.

You can find out with a simple command which year we have right now and can froce the program to add numbers from e.g. 1800 to the current year to your spinner.

WARNING: Pseudo code

Spinner mySpinner = (Spinner) findViewById(R.id.spinner);
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
ArrayAdapter<String> adapter;
List<String> list;

list = new ArrayList<String>();
for(int i = 1800; i <= year; i++)
{
  list.add(i);
}
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);