Date Picker in Android

Hello Guys !!

Here is the simple example of Date Picker in Android..



1. DatePickerActivity.java

package com.pack.datepicker;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.TextView;

public class DatePickerActivity extends Activity {
TextView textDate;
private int year;
private int month;
private int day;
static final int DATE_DIALOG_ID = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date_picker);
textDate = (TextView) findViewById(R.id.text_date);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
textDate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
}

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, year, month,
day);
}
return null;
} // updates the date we display in the TextView

private void updateDisplay() {
/* * Hide virtual keyboard */
textDate.setText(new StringBuilder()
// Month is 0 based so add 1
.append(year).append("-").append(month + 1).append("-")
.append(day).append(""));
}

private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int myear, int monthOfYear,
int dayOfMonth) {
year = myear;
month = monthOfYear;
day = dayOfMonth;
updateDisplay();
}
};
}


2. activity_date_picker.xml

<RelativeLayout 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"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/text_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Pick Date"
        android:textColor="#24B64E"
        android:textSize="22sp" />

</RelativeLayout>


Here is the output :




Happy Coding !!


Comments

Popular posts from this blog

Carousel view in Android

Get Phone Contacts and display in Listview in Android

Draw Pie Chart using Canvas and Third party Library in Android