Populate spinner with years dynamically in Android?

前端 未结 2 1271
广开言路
广开言路 2021-02-05 07:30

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

相关标签:
2条回答
  • 2021-02-05 07:52

    I hope it will help you.

    static final String[] Months = new String[] { "January", "February",
                "March", "April", "May", "June", "July", "August", "September",
                "October", "November", "December" };
    

     // Set years
            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.spinnerYears);
            spinYear.setAdapter(adapter);
            // Set months
            ArrayAdapter<String> adapterMonths = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, Months);
            adapterMonths.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    
            Spinner spinMonths = (Spinner)findViewById(R.id.spinnerMonths);
            spinMonths.setAdapter(adapterMonths);
            // Set days
            ArrayList<String> days = new ArrayList<String>();
            for (int i = 1; i <= 31; i++) {
                days.add(Integer.toString(i));
            }
            ArrayAdapter<String> adapterDays = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, days);
    
            Spinner spinDays = (Spinner)findViewById(R.id.spinnerDays);
            spinDays.setAdapter(adapterDays);
    
    0 讨论(0)
  • 2021-02-05 08:03

    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);
    
    0 讨论(0)
提交回复
热议问题