DatePicker Dialog

DatePicker Dialog in Android

Class FILE

package com.example.malik.test;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.Calendar;
public class MainActivity extends AppCompatActivity {

private Button button;
static final int DIALOG_ID = 0;
int year_x, month_x, day_x;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final Calendar cal = Calendar.getInstance();
year_x = cal.get(Calendar.YEAR);
month_x = cal.get(Calendar.MONTH);
day_x = cal.get(Calendar.DAY_OF_MONTH);

showDatePickerDialog();
}

private void showDatePickerDialog() {
button = (Button) findViewById(R.id.bDatePicker);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DIALOG_ID);
}
});
}

@Override
protected Dialog onCreateDialog(int id) {
if(id == DIALOG_ID)
return new DatePickerDialog(MainActivity.this, dPickeListner, year_x, month_x, day_x);
return null;
}

private DatePickerDialog.OnDateSetListener dPickeListner = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
year_x = year;
month_x = monthOfYear + 1;
day_x = dayOfMonth;
Toast.makeText(getApplicationContext(), year_x + “/” + month_x + “/” + day_x, Toast.LENGTH_SHORT).show();
}
};

}

 

XML  FILE

<?xml version=”1.0″ encoding=”utf-8″?>
<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”
android:paddingBottom=”@dimen/activity_vertical_margin”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
tools:context=”com.example.malik.test.MainActivity”>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Show Date Picker Dialog”
android:id=”@+id/bDatePicker”
android:layout_alignParentTop=”true”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”82dp” />

</RelativeLayout>

 

Output :

pic

 

Share

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.