Populate spinner with years dynamically in Android?

前端 未结 2 1274
广开言路
广开言路 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 years = new ArrayList();
            int thisYear = Calendar.getInstance().get(Calendar.YEAR);
            for (int i = 1900; i <= thisYear; i++) {
                years.add(Integer.toString(i));
            }
            ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, years);
    
            Spinner spinYear = (Spinner)findViewById(R.id.spinnerYears);
            spinYear.setAdapter(adapter);
            // Set months
            ArrayAdapter adapterMonths = new ArrayAdapter(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 days = new ArrayList();
            for (int i = 1; i <= 31; i++) {
                days.add(Integer.toString(i));
            }
            ArrayAdapter adapterDays = new ArrayAdapter(this, android.R.layout.simple_spinner_item, days);
    
            Spinner spinDays = (Spinner)findViewById(R.id.spinnerDays);
            spinDays.setAdapter(adapterDays);
    

提交回复
热议问题