安卓工作室中的日期选择器通过单击按钮

时间:2017-07-27 05:47:33

标签: android

我在editText中设置了一个日期选择器,它可以通过单击按钮来工作,所以我设置了onClick方法setDate和代码

public void setDate(View v){
        final Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dpd = new DatePickerDialog(this,new DatePickerDialog.OnDateSetListener(){
            @Override
            public void onDateSet(DatePicker view, int year, int monthofyear, int dayofmonth) {
                e5.setText(dayofmonth + "-" + monthofyear + "-" + year);
            }
        },day,month,year);
        dpd.show();
    }

但它不起作用。这是什么问题?

2 个答案:

答案 0 :(得分:0)

试试这个:

    textfield.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (view == dob) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

                    Date d = sdf.parse("31/12/2000");

                    fromDatePickerDialog.getDatePicker().setMaxDate(d.getTime());
                    fromDatePickerDialog.show();
                } catch (ParseException e) {
                    e.printStackTrace();
                }


           }
        }
    });

    final Calendar newCalendar = Calendar.getInstance();
    fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {



        public  void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            Calendar newDate = Calendar.getInstance();

            newDate.set(year, monthOfYear, dayOfMonth);

            textfield.setText(dateFormatter.format(newDate.getTime()));

        }

    },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));

答案 1 :(得分:0)

你可以这样做。

public void setDate(View v) {
    final Calendar c = Calendar.getInstance();
    year = c.get(Calendar.YEAR);
    month = c.get(Calendar.MONTH);
    day = c.get(Calendar.DAY_OF_MONTH);
    DatePickerDialog dpd = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthofyear, int dayofmonth) {
            e5.setText(dayofmonth + "-" + monthofyear + "-" + year);
        }
    }, year, month, day);
    dpd.show();
}

交换dayyear的排名。 希望能帮到你。