默认DatePicker对话框根据选择更改两个DatePicker日期

时间:2017-10-27 04:20:18

标签: android date android-fragments datepicker calendar

我有两个日期选择器对话框,我想根据两个对话框选择器的选择更改日期并设置最大值和最小值。     如果我选择"开始日期",结束日期应以"开始日期"开头。选择的值,如果我选择"结束日期"第一个"开始日期"最长日期应该是"结束日期"选定的价值。

private DatePickerDialog datePickerOne;
private DatePickerDialog datePickeTwo;

private void MyListener() { 
final Calendar calendarMain = Calendar.getInstance();
Year = calendarMain.get(Calendar.YEAR);
Month = calendarMain.get(Calendar.MONTH);
Day = calendarMain.get(Calendar.DAY_OF_MONTH);


datePickerOne = new DatePickerDialog(activity, new DatePickerDialog.OnDateSetListener() {

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

        Year = year;
        Month = monthOfYear;
        Day = dayOfMonth;

        StringBuilder selectedDateFrom = new StringBuilder().append(dayOfMonth).append("-").append(monthOfYear + 1).append("-").append(year);
        textDateStart.setText(selectedDateFrom);
        textDateStart.setTextColor(android.graphics.Color.BLACK);

        Calendar c2 = Calendar.getInstance();
            int yearResp=c2.get(Calendar.YEAR);
        int monthResp=c2.get(Calendar.MONTH);
        int dayResp=c2.get(Calendar.DAY_OF_MONTH);

        datePickerTwo.getDatePicker().setMinDate(c2.getTime().getTime());
         datePickerTwo.updateDate(dayResp, monthResp,yearResp);
        datePickerTwo.getDatePicker().setMaxDate(new Date().getTime()); 


    } 
}, Year, Month, Day); 

textDateStart.setOnClickListener(new View.OnClickListener() {
    @Override 
    public void onClick(View view) {

        datePickerOne.show(); 


    } 


}); 

datePickerTwo = new DatePickerDialog(activity, new DatePickerDialog.OnDateSetListener() {
    @Override 
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

        Year = year;
        Month = monthOfYear;
        Day = dayOfMonth;

        StringBuilder selectedDateTO = new StringBuilder().append(dayOfMonth).append("-").append(monthOfYear + 1).append("-").append(year);
        textDateEnd.setText(selectedDateTO);

        textDateEnd.setTextColor(android.graphics.Color.BLACK);

        Calendar c3 = Calendar.getInstance();
          int yearResp=c3.get(Calendar.YEAR);
        int monthResp=c3.get(Calendar.MONTH);
        int dayResp=c3.get(Calendar.DAY_OF_MONTH);
        datePickerOne.getDatePicker().setMaxDate(c3.getTime().getTime());
       datePickerOne.updateDate(dayResp, monthResp,yearResp);
        datePickerOne.getDatePicker().setMinDate(new Date().getTime()); 

    } 
}, Year, Month, Day); 

textDateEnd.setOnClickListener(new View.OnClickListener() {
    @Override 
    public void onClick(View view) {



        datePickerTwo.show(); 


    } 

}); 

现在只有我可以更改值的初始时间,下次不能正常工作。这里的datepicker对话框是datePickerOne和datePickerTwo。 textDateStart和textDateEnd是textviews。

1 个答案:

答案 0 :(得分:0)

您可以创建自己的日期选择器对话框片段并通过意图传递数据,并在调用者片段/活动的onActivityResult中获得所需的结果取决于您想要的位置以下代码可能对您有所帮助

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    public static final String FROM_DATE = "fromdate";
    public static final String TO_DATE = "todate";
    public static final String WHICH_DATE_TO_CHANGE = "which";
    private String fromDate;
    private String toDate;
    private int whichDate;

    public static final int FROM_DATE_FLAG = 0;
    public static final int TO_DATE_FLAG = 1;

    private Date fromDateObj;
    private Date toDateObj;


    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker

        String arra[] = null;
        fromDate = getArguments().getString(FROM_DATE);
        toDate = getArguments().getString(TO_DATE);
        whichDate = getArguments().getInt(WHICH_DATE_TO_CHANGE);

        initDateObjs();

        switch (whichDate) {

            case FROM_DATE_FLAG:

                arra = fromDate.split("-");

                break;
            case TO_DATE_FLAG:

                arra = toDate.split("-");

                break;

        }


        int year = Integer.parseInt(arra[0]);
        int month = Integer.parseInt(arra[1]) - 1;
        int day = Integer.parseInt(arra[2]);


        android.app.DatePickerDialog datePickerDialog = null;
        // Create a new instance of DatePickerDialog and return it
        if (Build.VERSION.SDK_INT >= 21) {

            datePickerDialog = new android.app.DatePickerDialog(getActivity(), R.style.DialogFragmentTheme, this, year, month, day);

        } else {
            datePickerDialog = new android.app.DatePickerDialog(getActivity(), this, year, month, day);

        }

        datePickerDialog.getDatePicker().setMinDate(getMinDate());
        datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() - 1000);

        return datePickerDialog;
    }


    public void initDateObjs() {


        fromDateObj=getDateobject(fromDate);
        toDateObj=getDateobject(toDate);


    }


    public Date getDateobject(String dateStr) {


        //fromDateObj;
        //toDateObj;
        String arra[] = null;
        arra = dateStr.split("-");
        int year = Integer.parseInt(arra[0]);
        int month = Integer.parseInt(arra[1]) - 1;
        int day = Integer.parseInt(arra[2]);

        Calendar cal = Calendar.getInstance();
        cal.set(year, month, day);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }





    public static long getMinDate() {
        //        getting date 30 days back for data of graph
       /* SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date parsedDate = formatter.parse(dateInString);*/
        Calendar cal = Calendar.getInstance();

/*
        cal.set(someTimeDuringYear1, someTimeDuringMonth1 - 1, someTimeDuringDay1);
*/
        cal.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR_OF_DAY));
        cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE));
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);

//       Calendar.add(Calendar.DAY_OF_YEAR, -15)
//      first parameter is represent days of year and second is how many days before the current date
        cal.add(Calendar.MONTH, -11);
        return cal.getTime().getTime();


    }


    public boolean vaidatePickedDate(String picekdDate) {


        boolean flag=true;

        Date date=getDateobject(picekdDate);

        switch (whichDate) {

            case FROM_DATE_FLAG:

                if(date.compareTo(toDateObj)>0){


                    // error
                    flag=false;
                }

                break;
            case TO_DATE_FLAG:

                if(date.compareTo(fromDateObj)<0){

                    flag=false;
                }

                break;

        }


        return flag;
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        Intent intent = new Intent();
        //yyyy-MM-dd
        monthOfYear = monthOfYear + 1;
        String day = String.valueOf(dayOfMonth);
        String month = String.valueOf(monthOfYear);
        if (day.length() == 1) {

            day = "0" + dayOfMonth;
        }
        if (month.length() == 1) {

            month = "0" + monthOfYear;
        }
        String dateRes=year + "-" + month + "-" + day;
        intent.putExtra("date",dateRes );


        if(vaidatePickedDate(dateRes)){

            getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);
            dismiss();

        }else {

            showErrorMessage();
        }
    }

    public void showErrorMessage(){

        switch (whichDate){


            case FROM_DATE_FLAG:

                Toast.makeText(getActivity(),getString(R.string.from_date_error),Toast.LENGTH_SHORT).show();
                break;
            case TO_DATE_FLAG:

                Toast.makeText(getActivity(),getString(R.string.to_date_error),Toast.LENGTH_SHORT).show();
                break;
        }

    }

    @Override
    public void onCancel(DialogInterface dialog) {
        super.onCancel(dialog);

        if (getParentFragment() instanceof DialogInterface.OnCancelListener)
            ((DialogInterface.OnCancelListener) getParentFragment()).onCancel(dialog);
    }

    public static String getCurrentTimeStamp() {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss");
        return simpleDateFormat.format(new Date());
    }

}

以下代码用于调用此datepicker对话框片段,这是我根据我的要求编写的,您必须根据您的要求进行更改

int requestCode=123;
 DatePickerFragment datePickerFragment = new DatePickerFragment();
        Bundle b = new Bundle();
        b.putString(DatePickerFragment.FROM_DATE,
                start_date_textview.getText().toString());
        b.putString(DatePickerFragment.TO_DATE,
                end_date_textview.getText().toString());
        b.putInt(DatePickerFragment.WHICH_DATE_TO_CHANGE, whichDateToChange); //whichDateToChange is a flag to identify either its start date or end date 
        datePickerFragment.setArguments(b);
        datePickerFragment.setTargetFragment(this, requestCode);
        datePickerFragment.show(getChildFragmentManager(), "");

您将在onActivityResult

中获得结果