Saturday, September 24, 2016

Date Picker Android

-MainActivity.java

package com.manish.datepikerdemo;

import java.util.Calendar;

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

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity 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_main);
  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();
  }
 };
}

3-activity_main.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:textSize="22sp"
        android:textColor="#FF0000"
        android:text="Pick Date" />

</RelativeLayout>

No comments:

Post a Comment