activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/datePicker1"
android:layout_marginLeft="100dp"
android:text="Get Date" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginLeft="100dp"
android:layout_marginTop="10dp"
android:textStyle="bold"
android:textSize="18dp"/>
</RelativeLayout>
MainActivity.java
package com.example.datepickerexample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
DatePicker picker;
Button btnGet;
TextView tvw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvw=(TextView)findViewById(R.id.textView1);
picker=(DatePicker)findViewById(R.id.datePicker1);
btnGet=(Button)findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvw.setText("Selected Date: "+ picker.getDayOfMonth()+"/"+ (picker.getMonth() + 1)+"/"+picker.getYear());
}
});
}
}