Android DatePicker is a widget to select date. It allows you to select date by day, month and year. Like DatePicker, android also provides TimePicker to select time.
The android.widget.DatePicker is the subclass of FrameLayout class.
Android DatePicker Example
Let's see the simple example of datepicker widget in android.
activity_main.xml
File: activity_main.xml
- <RelativeLayout xmlns:androclass="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/textView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true"
- android:layout_marginLeft="50dp"
- android:layout_marginTop="36dp"
- android:text="Current Date:" />
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentBottom="true"
- android:layout_centerHorizontal="true"
- android:layout_marginBottom="140dp"
- android:text="Change Date" />
- <DatePicker
- android:id="@+id/datePicker1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_above="@+id/button1"
- android:layout_centerHorizontal="true"
- android:layout_marginBottom="30dp" />
- </RelativeLayout>
Activity class
File: MainActivity.java
- package com.example.datepicker2;
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.DatePicker;
- import android.widget.TextView;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- DatePicker picker;
- Button displayDate;
- TextView textview1;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- textview1=(TextView)findViewById(R.id.textView1);
- picker=(DatePicker)findViewById(R.id.datePicker1);
- displayDate=(Button)findViewById(R.id.button1);
- textview1.setText(getCurrentDate());
- displayDate.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View view) {
- textview1.setText(getCurrentDate());
- }
- });
- }
- public String getCurrentDate(){
- StringBuilder builder=new StringBuilder();
- builder.append("Current Date: ");
- builder.append((picker.getMonth() + 1)+"/");//month is 0 based
- builder.append(picker.getDayOfMonth()+"/");
- builder.append(picker.getYear());
- return builder.toString();
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.activity_main, menu);
- return true;
- }
- }
most easy way to use datepicker and well explained by you kundan
ReplyDelete