Android Spinner使用for循环的动态值

时间:2017-04-19 06:53:34

标签: android android-spinner

我希望有一个旋转器,其动态值为1-12,第1-31天,以及从1917年到当年的一年。

<LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    <Spinner
        android:id="@+id/spinner_Month"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Spinner
        android:id="@+id/spinner_Day"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Spinner
        android:id="@+id/spinner_Year"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>


    List year = new ArrayList<Integer>();
    for (int i = 1917; i <= "IwantThisTobeInCurrentYear - 18"; i++) {
        year.add(Integer.toString(i));
    }
    ArrayAdapter<Integer> spinnerArrayAdapter = new ArrayAdapter<Integer>(
            this, android.R.layout.simple_spinner_item, year);
    spinnerArrayAdapter.setDropDownViewResource( 
    android.R.layout.simple_spinner_dropdown_item );

    Spinner spinner = (Spinner)findViewById(R.id.years_spinner);
    spinner.setAdapter(spinnerArrayAdapter);

并且在for循环中我希望这是当前年份 - 18要避免少于18。 我想将默认值设置为YEAR或YYYY

1 个答案:

答案 0 :(得分:1)

请尝试使用DatePickerDialog

1。创建DatePickerDialog.OnDateSetListener

DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,
                          int dayOfMonth) {

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, monthOfYear);
        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

        String dateFormat = "MM/dd/yy"; //Change date format if required
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.ENGLISH);

        String dateStr = sdf.format(calendar.getTime());

        EditText editText = null; //initialize edit text here
        editText.setText(dateStr);
        //use this date
    }

};

2. 按钮点击等显示日期选择器

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        Calendar calendar = Calendar.getInstance();

        DatePickerDialog datePickerDialog =new DatePickerDialog(context, datePickerListener,calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
    }
});