如何从日期选择器获取日期仅一个月和一年

时间:2014-12-11 06:51:28

标签: android

//Edit Text

we_join_et = (EditText) findViewById(R.id.we_join_et);

//OnClick for Edittext

        we_join_et.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            createDialogWithoutDateField().show();

        }
    });

//createDialogWithoutDateField Method

    private DatePickerDialog createDialogWithoutDateField() {

    DatePickerDialog dpd = new DatePickerDialog(this, null, 2014, 1, 24);
    try {
        java.lang.reflect.Field[] datePickerDialogFields = dpd.getClass()
                .getDeclaredFields();
        for (java.lang.reflect.Field datePickerDialogField : datePickerDialogFields) {
            if (datePickerDialogField.getName().equals("mDatePicker")) {
                datePickerDialogField.setAccessible(true);
                DatePicker datePicker = (DatePicker) datePickerDialogField
                        .get(dpd);
                java.lang.reflect.Field[] datePickerFields = datePickerDialogField
                        .getType().getDeclaredFields();
                for (java.lang.reflect.Field datePickerField : datePickerFields) {
                    Log.i("test", datePickerField.getName());
                    if ("mDaySpinner".equals(datePickerField.getName())) {
                        datePickerField.setAccessible(true);
                        Object dayPicker = new Object();
                        dayPicker = datePickerField.get(datePicker);
                        ((View) dayPicker).setVisibility(View.GONE);
                    }
                }
            }

        }
    } catch (Exception ex) {
    }
    System.out.println(dpd);
    return dpd;
}

如何从上面的方法返回值Moth和Year,我不知道在哪里使用OnDateSetListener(),以便我可以在用户进行日期更改时设置日期。在此先感谢。

1 个答案:

答案 0 :(得分:0)

实施OnDateSetListener:

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
   // when dialog box is closed, below method will be called.
   public void onDateSet(DatePicker view, int selectedYear,int selectedMonth, int selectedDay) {
      String year1 = String.valueOf(selectedYear);
      String month1 = String.valueOf(selectedMonth + 1);
      we_join_et.setText( month1 + "-" + year1);
   }
};

将OnDateSetListener设置为DatePickerDialog:

DatePickerDialog dpd = new DatePickerDialog(this, datePickerListener, 2014, 1, 24);