Skip to content Skip to sidebar Skip to footer

Getting Data From A DatePickerDialog To A Fragment

As above I am trying to work out how to pass back the date selected by the user. I have worked out how to get the date selected by using the onDateSet method but I do not know how

Solution 1:

You can set DateListner on Edittext onClicklistner..

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

public class DateListener implements OnClickListener, OnDateSetListener {

    private Activity activity;

    private int year;
    private int monthOfYear;
    private int dayOfMonth;

    private View touchedView;

    public DateListener(Activity activity) {
        this.activity = activity;
        final Calendar c = Calendar.getInstance();
        this.year = c.get(Calendar.YEAR);
        this.monthOfYear = c.get(Calendar.MONTH);
        this.dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
    }

    public int getYear() {
        return year;
    }
    public int getMonth() {
        return monthOfYear;
    }
    public int getDay() {
        return dayOfMonth;
    }

    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        this.year = year;
        this.monthOfYear = monthOfYear + 1;
        this.dayOfMonth = dayOfMonth;

        updateDisplay();
        updateEditText();
    }

    @Override
    public void onClick(View v) {
        touchedView = v;

        new DatePickerDialog(activity,
                this, this.getYear(), this.getMonth(), this.getDay()).show();
    }

    private void updateDisplay() {
        ((TextView) touchedView).setText(
            new StringBuilder()
                    .append(pad(dayOfMonth)).append(".")
                    .append(pad(monthOfYear)).append(".")
                    .append(pad(year)));
    }

    private void updateEditText() {
        ((EditText) touchedView).setText(
            new StringBuilder()
                    .append(pad(dayOfMonth)).append(".")
                    .append(pad(monthOfYear)).append(".")
                    .append(pad(year)));
    }

    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }

}

In Your Fragment

DateListener dateListener = new DateListener(getActivity());

edittext.setOnClickListener(dateListener);


Post a Comment for "Getting Data From A DatePickerDialog To A Fragment"