Android 自定义带两个DatePicker的DatePickerDialog

  今天介绍一下自定义带两个DatePicker的Dialog,首先xml布局/res/layout/custom_date_picker.xml:



    

    

  代码:

// These variables will hold the date values later
private int startYear, startMonth, startDay, endYear, endMonth, endDay;

/**
 * Displays the start and end date picker dialog
 */
public void showDatePicker() {
    // Inflate your custom layout containing 2 DatePickers
    LayoutInflater inflater = (LayoutInflater) getLayoutInflater();
    View customView = inflater.inflate(R.layout.custom_date_picker, null);

    // Define your date pickers
    final DatePicker dpStartDate = (DatePicker) customView.findViewById(R.id.dpStartDate);
    final DatePicker dpEndDate = (DatePicker) customView.findViewById(R.id.dpEndDate);

    // Build the dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(customView); // Set the view of the dialog to your custom layout
    builder.setTitle("Select start and end date");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener(){
        @Override
        public void onClick(DialogInterface dialog, int which) {
            startYear = dpStartDate.getYear();
            startMonth = dpStartDate.getMonth();
            startDay = dpStartDate.getDayOfMonth();
            endYear = dpEndDate.getYear();
            endMonth = dpEndDate.getMonth();
            endDay = dpEndDate.getDayOfMonth();
            dialog.dismiss();
        }});

    // Create and show the dialog
    builder.create().show();
}

  效果图:

Android 自定义带两个DatePicker的DatePickerDialog_第1张图片
 

你可能感兴趣的:(Android)