填充微调多年在动态的Android?(Populate spinner with years dyn

2019-08-21 03:00发布

我一直在货架我的大脑试图得到这个工作。 我想从1900年中动态地进入到本年度进入微调。 我不认为这是可能的使用XML定义的数组做的,但我可以用一个阵列适配器办呢? 这是我到目前为止有:

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

下面是微调的XML:

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

谢谢你的帮助。

Answer 1:

你非常接近。 试试这个:

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

你刚才忘了加

spinYear.setAdapter(adapter);


Answer 2:

我希望这会帮助你。

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


文章来源: Populate spinner with years dynamically in Android?