DatePicker Example in android - android

Please suggest me some tutorial which gives the example for DatePicker and how to use its methods like OnDateChangedListener, onDateChanged etc. Actually I am going through some sites, but i did not get the clear idea of it.
Thank you

Android references on DatePicker is quite good. Have a look at it here.
private DatePicker datePicker;
//monthofYear is between 0-11
datePicker.init(2010, 11, 1, new OnDateChangedListener() {
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
// Notify the user.
}
});

See.Example(); here

Check this Data Picker example: Example of DATE PICKER .

Step 1 : create a java file:
package com.example.babs;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.app.FragmentManager;
public class EditUserInfo extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_edit_view);
}
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
// pgrm mark ---- ---- ----- ---- ---- ----- ---- ---- ----- ---- ---- -----
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
public void showDatePickerDialog(View v) {
FragmentManager fragmentManager = getFragmentManager();
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(fragmentManager, "datePicker");
}
}// end main class EditUserInfo
step 2: your xml file must contain :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:fillViewport="true" >
</ScrollView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pick_date"
android:onClick="showDatePickerDialog" />

You can try this code:
public
static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
DateEdit.setText(day + "/" + (month + 1) + "/" + year);
}
}
Taken from Example of DatePickerFragment and TimePickerFragment.

Related

How to set a minimum date for an EditText field?

I'm trying to set a minimum date (which is supposed to be the current date) so that the user won't be able to select a date older than today. I'm working in a fragment as you can see. I already searched for help but either it wasn't clear to me since i'm just starting with coding or i just failed to use it. Here is what i coded until now but i can't go further.
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
Calendar cal = new GregorianCalendar(year, month, day);
setDate(cal);
}
protected void setDate(final Calendar calendar) {
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
((TextView) getActivity().findViewById(R.id.datenaissance)).setText(dateFormat.format(calendar.getTime()));
}
}
Here is the second fragment i'm working with:
package cm.opep.opep.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import cm.opep.opep.R;
public class RegistrationFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_registration, container, false);
initUI(v);
return v;
}
private void initUI(View v){
//Lancement de la date de naissance
EditText datenaissance = (EditText) v.findViewById(R.id.datenaissance);
datenaissance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatePickerFragment fragment = new DatePickerFragment();
fragment.show(getFragmentManager(), "datePicker");
}
});
}
}
Here's the XML code:
<LinearLayout xmlns
android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/white"
tools:context="cm.opep.opep.Tiroir$PlaceholderFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="UselessParent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/datenaissance"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:hint="#string/date_de_naissance"
android:inputType="date"
android:textColor="#color/colorPrimaryDark"
android:textSize="12sp"
android:onClick="datePicker"
android:focusable="False"
android:layout_marginStart="40dp"
android:layout_marginEnd="40dp"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
Any help will be appreciated. Thanks
All you need to do is create an instance of DatePickerDialog and using the 'set min date()' function.
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
// Here you can set the minimum date on date picker ********
dialog.getDatePicker().setMinDate(new Date().getTime());
return dialog;
}
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
Calendar cal = new GregorianCalendar(year, month, day);
setDate(cal);
}
protected void setDate(final Calendar calendar) {
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
((TextView) getActivity().findViewById(R.id.datenaissance)).setText(dateFormat.format(calendar.getTime()));
}
}
or you can use this class:
public class StartDatePicker extends DialogFragment implements DatePickerDialog.OnDateSetListener {
Calendar c = Calendar.getInstance();
int startYear = c.get(Calendar.YEAR);
int startMonth = c.get(Calendar.MONTH);
int startDay = c.get(Calendar.DAY_OF_MONTH);
SharedPreferences objSharedPreferences;
SharedPreferences.Editor objEditor;
private Activity activity;
private View component;
public StartDatePicker(Activity activity, View component) {
this.activity = activity;
this.component = component;
createSharedPreferences();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// TODO Auto-generated method stub
// Use the current date as the default date in the picker
DatePickerDialog dialog = new DatePickerDialog(activity, this, startYear, startMonth, startDay);
// dialog.getDatePicker().setMaxDate(new Date().getTime());
// dialog.getDatePicker().setMinDate(new Date().getTime());
return dialog;
}
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
try {
startDay = dayOfMonth;
startMonth = monthOfYear + 1;
startYear = year;
String dateToBeSet = startDay + "-" + getMonth(startMonth) + "-" + startYear;
if (component instanceof EditText) {
((EditText) component).setText(dateToBeSet);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month - 1].substring(0, 3);
}
}
On editText click use this code :
DialogFragment dialogFragment = new StartDatePicker(this, fromDateEditText);
dialogFragment.show(getFragmentManager(), "start_date_picker");

DateTimePicker run different depends on api level in Android

I want to use Date Time picker in my project .
http://www.parallelcodes.com/android-datetime-picker-example/
This tutorial works perfectly. When I run this datetimepicker in api 19 showing like this web site and I want to do this.
When I run api 22 datetimepicker appear like this.
So, Any suggestions?
I used this code to solve this issue,
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import java.util.Calendar;
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
private Calendar calendar;
private Calendar maxCalendar;
private Calendar minCalendar;
private DatePickerDialog.OnDateSetListener onDateSetListener;
private static final String TAG = DatePickerFragment.class.getSimpleName();
public void setup(Calendar calendar, DatePickerDialog.OnDateSetListener onDateSetListener){
this.calendar = calendar;
this.onDateSetListener = onDateSetListener;
}
public void setup(Calendar calendar, Calendar maxCalendar, DatePickerDialog.OnDateSetListener onDateSetListener){
this.calendar = calendar;
this.maxCalendar = maxCalendar;
this.onDateSetListener = onDateSetListener;
}
public void setup(Calendar calendar, Calendar maxCalendar, Calendar minCalendar){
this.calendar = calendar;
this.maxCalendar = maxCalendar;
this.minCalendar = minCalendar;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(getActivity(),android.R.style.Theme_Holo_Light_Dialog_MinWidth, this, year, month, day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
if(minCalendar!=null){
dialog.getDatePicker().setMinDate(minCalendar.getTimeInMillis());
}
if(maxCalendar != null){
dialog.getDatePicker().setMaxDate(maxCalendar.getTimeInMillis());
}
return dialog;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
if(onDateSetListener != null){
onDateSetListener.onDateSet(view, year, month, day);
}else{
Log.w(TAG, "onDateSetListener callback is not initialized.");
}
}
}
and call like this ,
public void showDatePicker() {
Calendar calendar = Calendar.getInstance();
DatePickerFragment fragment = new DatePickerFragment();
fragment.setup(calendar, new OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
}
});
fragment.show(getSupportFragmentManager(), null);
}
This is android own calendar which design changes for different API. If you want to use same calendar for all API version then you should try with a custom calendar rather then default calendar
If still have any confusion then please let me know

How to get date "value" from DatePicker?

I don't know how to get the date value from Datepicker.
PickerDialog.java
package com.example.alecksjohanssen.newyorktimes;
/**
* Created by AlecksJohanssen on 3/19/2016.
*/
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import java.util.Calendar;
public class PickerDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{ DateSettings dateSettings = new DateSettings(getActivity());
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int dayofmonth = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog;
dialog = new DatePickerDialog(getActivity(),dateSettings,year,month,dayofmonth);
return dialog;
}
}
DateSetting.java
package com.example.alecksjohanssen.newyorktimes;
import android.app.DatePickerDialog;
import android.content.Context;
import android.widget.DatePicker;
import android.widget.Toast;
/**
* Created by My name Is Hardline on 2/26/2016.
*/
public class DateSettings implements DatePickerDialog.OnDateSetListener {
Context context;
public DateSettings(Context context) {
this.context = context;
}
#Override
public void onDateSet(DatePicker view, int year, int monthofyear,int dayofmonth) {
Toast.makeText(context, "Selected date" + monthofyear + "/" + dayofmonth + "/" + year, Toast.LENGTH_LONG).show();
}
}
public void setDate() {
PickerDialog pickerDialogs = new PickerDialog();
pickerDialogs.show(getFragmentManager(), "date_picker");
}
It's basically it, it's only shows that Selected date is . Still I'm looking for how to extract the date data so that I can put it on my Begin Date :P.
You can try like this
private void datePicker(){
Calendar calendar = Calendar.getInstance();
final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
DatePickerDialog datePickerDialog = new DatePickerDialog(activity, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
System.out.print(dateFormatter.format(newDate.getTime()));
}
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
Say you have Calendar mCalendar that you want to init the date picker with it.
dialog.getDatePicker().init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {
#Override
public void onDateChanged(DatePicker datePicker, int i, int i2, int i3) {
mCalendar.set(i, i2, i3);
}
});
Then to get the picked date
mCalendar.getTime()

calendarViewShown is not being honored on Android 5.0 Lollipop

I am working through The Big Nerd Ranch's Android Guide. In the
assignment Criminal Intent I am using DatePicker with following
layout.
On pre-5.0 devices, calendar is not shown in DatePicker as defined in
the layout but Android 5.0 ignores this and shows a calendar. Any idea
what might be going on here?
Full code is available on Github.
dialog_date.xml
<?xml version="1.0" encoding="utf-8"?>
<DatePicker xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dialog_date_datePicker"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:calendarViewShown="false" >
</DatePicker>
DatePickerFragment.java
package com.sudhirkhanger.android.criminalintent;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
public class DatePickerFragment extends DialogFragment {
public static final String EXTRA_DATE = "com.sudhirkhanger.android.criminalintent.date";
private Date mDate;
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_DATE, date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
private void sendResult(int resultCode) {
if (getTargetFragment() == null)
return;
Intent i = new Intent();
i.putExtra(EXTRA_DATE, mDate);
getTargetFragment().onActivityResult(getTargetRequestCode(),
resultCode, i);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mDate = (Date) getArguments().getSerializable(EXTRA_DATE);
// Create a Calendar to get the year, month, and day
final Calendar calendar = Calendar.getInstance();
// calendar.setTime(mDate);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
View v = getActivity().getLayoutInflater().inflate(
R.layout.dialog_date, null);
DatePicker datePicker = (DatePicker) v
.findViewById(R.id.dialog_date_datePicker);
datePicker.init(year, month, day, new OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year, int month,
int day) {
// Translate year, month, day into a Date object using a
// calendar
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
mDate = new GregorianCalendar(year, month, day, hour, minute)
.getTime();
// Update argument to preserve selected value on rotation
getArguments().putSerializable(EXTRA_DATE, mDate);
}
});
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
sendResult(Activity.RESULT_OK);
}
}).create();
}
}
The solution has been posted here
You have to use both android:calendarViewShown="false" and android:datePickerMode="spinner".
This solves it.
<DatePicker xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dialog_date_datePicker"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:calendarViewShown="false"
android:datePickerMode="spinner" >
</DatePicker>
Below code worked for me
new DatePickerDialog(getActivity(),android.R.style.Theme_Holo_Dialog, this, year,month, day);

Datepicker created with DialopFragment showing Calender also

I am new to Android programming and I am using a basic Datepicker created using a DialogFragment. My DatePicker shows up fine on click etc., but the problem is that it is displaying the Calendar view as well. I do not want this. I have been searching for a solution for a day now, and I am unwilling to use custom Datepickers right now, as I want to get familiar with the basics first.
I have also read suggestions such as
yourDatepicker.setCalendarViewShown(false);
or set it to false in the XML. But my DatePicker comes from a DialogFragment, so how do I access this datepicker? How do I set its final view? I do not wish to make changes in the source code as I am still learning the ropes.
My datepicker code:
public class DueDatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day){
// Code to set Due Date TextField to the selected date.
TextView reminderText = (TextView)getActivity().findViewById(R.id.addTaskFormDueDateHolder);
String dueDateStr = year + "-" + month + "-" + day;
reminderText.setText(dueDateStr);
}
}
I have used Datepicker Dialog Fragment, to show the Date picker in dialog.
Here is my Complete Code
MainActivity.java
package com.example.testmydrag;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.DatePicker;
import android.support.v4.app.FragmentActivity;
import android.app.Dialog;
import android.app.DatePickerDialog;
import android.support.v4.app.DialogFragment;
import java.util.Calendar;
public class MainActivity extends FragmentActivity {
EditText mEdit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void selectDate(View view) {
DialogFragment newFragment = new SelectDateFragment();
newFragment.show(getSupportFragmentManager(), "DatePicker");
}
public void setTheDate(int year, int month, int day) {
mEdit = (EditText)findViewById(R.id.Text);
mEdit.setText(month+"/"+day+"/"+year);
}
/*
* Date Picker Dialog
*/
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int yy = c.get(Calendar.YEAR);
int mm = c.get(Calendar.MONTH);
int dd = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(getActivity(),this,c.YEAR, c.MONTH, c.DATE);
/*Calendar View if you want to Remove Set it to False*/
dialog.getDatePicker().setCalendarViewShown(true);
/*Spinner View if you want to Show Set it to True*/
dialog.getDatePicker().setSpinnersShown(false);
dialog.setTitle("Pick a date");
return dialog;
}
public void onDateSet(DatePicker view, int yy, int mm, int dd) {
setTheDate(yy, mm+1, dd);
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText android:text="#+string/date_text"
android:id="#+id/Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+string/pick_date"
android:onClick="selectDate" />
</LinearLayout>
I found a temporary solution, though I am not entirely happy with it. You need minimum SDK version 11 for this.
Basically I added a call to getDatePicker() in my onAcreateDialog function, mentioned in the DueDatePickerFragment, and then changed its settings. I don't understand why I need to do this, and why it is appearing so incorrectly in my emulator. No one else seems to be having this problem. Any explanations would be highly appreciated. Here is the code:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
Log.i("DUEDATEPICKERDIALOG", "Inside onCreateDIALOG");
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialogObj = new DatePickerDialog(getActivity(), this, year, month, day);
DatePicker dueDatePicker = datePickerDialogObj.getDatePicker();
float scaleVal = (float) 0.6;
dueDatePicker.setScaleX(scaleVal);
dueDatePicker.setScaleY(scaleVal);
dueDatePicker.setCalendarViewShown(false);
return datePickerDialogObj;
}
Hope this helps someone.

Categories

Resources