de.uni_koblenz_landau.apow.dialogs.DateDialogFragment.java Source code

Java tutorial

Introduction

Here is the source code for de.uni_koblenz_landau.apow.dialogs.DateDialogFragment.java

Source

/**
 * Apow - a mobile EHR Management System for low-resource environments
 * in developing countries, exemplified by rural Ghana
 * Copyright (C) 2014 Martin Landua
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
 */

package de.uni_koblenz_landau.apow.dialogs;

import java.util.Calendar;
import java.util.Date;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;

/**
 * Implements a Dialog to pick a date.
 * @author Martin Landua
 *
 */
public class DateDialogFragment extends DialogFragment {

    private static Calendar mCalendar;
    private static DateDialogListener mListener;
    private static String mTarget;

    public static DateDialogFragment newInstance(Calendar date) {
        DateDialogFragment dialog = new DateDialogFragment();

        mCalendar = Calendar.getInstance();
        mCalendar = date;
        return dialog;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        setRetainInstance(true);
        mTarget = this.getTag();
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), dateSetListener, mCalendar.get(Calendar.YEAR),
                mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH));
        dialog.getDatePicker().setMaxDate(new Date().getTime());
        return dialog;
    }

    public void setListener(DateDialogListener listener) {
        mListener = listener;
    }

    private final DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {

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

            mCalendar = Calendar.getInstance();
            mCalendar.set(year, monthOfYear, dayOfMonth);

            // Callback to listener
            mListener.dateSet(mCalendar, mTarget);
        }
    };

    @Override
    public void onDestroyView() {
        if (getDialog() != null && getRetainInstance()) {
            getDialog().setDismissMessage(null);
        }
        super.onDestroyView();
    }
}