DatePicker
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="50dp" android:layout_marginStart="50dp" android:layout_marginLeft="50dp" android:layout_marginTop="50dp" android:layout_marginEnd="50dp" android:layout_marginRight="50dp" android:layout_marginBottom="50dp" android:orientation="vertical" tools:context=".MainActivity">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="50dp"
android:layout_marginStart="50dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="50dp"
android:layout_marginRight="50dp"
android:layout_marginBottom="50dp"
android:text="Pick Date" />
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="50dp"
android:layout_marginStart="50dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="50dp"
android:layout_marginRight="50dp"
android:layout_marginBottom="50dp"
android:text="Today's Date" />
</LinearLayout>
Java:
package com.example.datepicker;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private TextView tv;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tv);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDatePicker();
}
});
}
private void showDatePicker(){
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
String selectedDate = dayOfMonth + "/" + (month + 1) + "/" + year;
tv.setText(selectedDate);
Toast.makeText(MainActivity.this, selectedDate, Toast.LENGTH_SHORT).show();
}
}, year, month, day);
datePickerDialog.show();
}
}