示意图:
layout布局文件:xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"tools:context=".MainActivity"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><TextViewandroid:layout_width="wrap_content"android:layout_height="match_parent"android:text="DatePicker(日期选择器):"android:textSize="24sp"/><DatePickerandroid:id="@+id/btnDp"android:layout_width="match_parent"android:layout_height="wrap_content"/><DatePickerandroid:calendarTextColor="#ff00ff"android:layout_width="match_parent"android:layout_height="wrap_content"android:datePickerMode="spinner"android:headerBackground="#ff00ff00"/><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="TimePicker(时间选择器)"android:textSize="24sp"android:gravity="center"/><TimePickerandroid:id="@+id/btnTp"android:layout_width="match_parent"android:layout_height="wrap_content"/><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="CalendarView(日历视图)"android:textSize="24sp"android:gravity="center"/><CalendarViewandroid:id="@+id/btnCv"android:layout_width="match_parent"android:layout_height="wrap_content"/></LinearLayout></ScrollView>
MainActivity:
package com.example.mydate;import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;public class MainActivity extends AppCompatActivity implements DatePicker.OnDateChangedListener,CalendarView.OnDateChangeListener,TimePicker.OnTimeChangedListener{//定义组件 都继承 FrameLayout 帧布局private DatePicker datePicker;private TimePicker timePicker;private CalendarView calendarView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);datePicker = findViewById(R.id.btnDp);timePicker = findViewById(R.id.btnTp);calendarView = findViewById(R.id.btnCv);//绑定事件 日期datePicker.setOnDateChangedListener(this);//时间timePicker.setOnTimeChangedListener(this);//日期calendarView.setOnDateChangeListener(this);}@Overridepublic void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {Toast.makeText(this,year+"-年-"+(monthOfYear+1)+"-月-"+dayOfMonth+"-日",Toast.LENGTH_SHORT).show();}@Overridepublic void onTimeChanged(TimePicker view, int hourOfDay, int minute) {Toast.makeText(this,hourOfDay+"-小时"+minute+"-分钟-",Toast.LENGTH_SHORT).show();}@Overridepublic void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {Toast.makeText(this,"您选择了"+year+"-年-"+(month+1)+"-月-"+dayOfMonth+"-日",Toast.LENGTH_SHORT).show();}
}