Android custom date picker

Home  >>  Tutorials  >>  Android  >>  Android custom date picker

Android custom date picker

1
Mar,2018

0

Step -1 :

Create a custom fragment

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;

import java.text.SimpleDateFormat;
import java.util.Calendar;


@SuppressLint("ValidFragment")
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {


    public static final String DATE_FORMAT = "dd-MM-yyyy";
    EditText mView;

    private DatePickerDialog datepic;

    public DatePickerFragment(View v) {
        mView = (EditText) v;
    }


    Calendar c;

    public DatePickerFragment() {
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);


        datepic = new DatePickerDialog(getActivity(), this, year, month, day);
        DatePicker dp = datepic.getDatePicker();
        dp.setMinDate(c.getTimeInMillis() + 60 * 60 * 24 * 1000);
        dp.setMaxDate(c.getTimeInMillis() + 60 * 60 * 24 * 1000 * 16);
        return datepic;
    }


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


        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, monthOfYear);
        c.set(Calendar.DAY_OF_MONTH, dayOfMonth);

        // String years=Integer.toString(dayOfMonth);

        updateDateButtonText((EditText) mView);


    }

    private void updateDateButtonText(EditText mView) {

        SimpleDateFormat timeFormat = new SimpleDateFormat(DATE_FORMAT);
        String timeForButton = timeFormat.format(c.getTime());
        mView.setText(timeForButton);
    }


}

Step 2 : Create an EditText and call it in activity .Like this

private EditText dob;
dob = findViewById(R.id.date_of_birth);

Step 3 :
Create a click listener of dob

dob.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        DialogFragment fragment = new DatePickerFragment(dob);
        fragmentTransaction.addToBackStack(null);
        fragment.show(fragmentTransaction, "Set Date");
    }
});

Step 4 : set dob text to dob edittext

dob.setText(dob.getText().toString());

Leave a Reply

Your email address will not be published. Required fields are marked *