package com.example.administrator.mytest; import android.annotation.TargetApi; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.DialogInterface; import android.icu.util.Calendar; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private int myear,mmonth,mday; Button bt_1; TextView dateDisplay; static final int Date_Dialog_Id=0; //日期被设置时候触发监听器 private DatePickerDialog.OnDateSetListener os1=new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { myear=year; mmonth=monthOfYear; mday=dayOfMonth; dateDisplay.setText(myear+"-"+mmonth+"-"+mday); } }; //创建一个新的窗口然后返回 @Override protected Dialog onCreateDialog(int id) { switch (id) { case Date_Dialog_Id: return new DatePickerDialog(this,os1,myear,mmonth,mday); } return null; } @TargetApi(Build.VERSION_CODES.N) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Calendar c=Calendar.getInstance(); myear=c.get(Calendar.DAY_OF_YEAR); mmonth=c.get(Calendar.MONTH); mday=c.get(Calendar.DAY_OF_MONTH); dateDisplay=(TextView)findViewById(R.id.tv_1); bt_1=(Button)findViewById(R.id.bt_1); bt_1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //重写其内部方法来显示窗口 showDialog(Date_Dialog_Id); } }); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" tools:context="com.example.administrator.mytest.MainActivity" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/tv_1" android:layout_marginTop="20dp" android:text="请设置日期" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="请设置时间" android:layout_marginTop="50dp" android:id="@+id/bt_1"/> </LinearLayout>
原文:http://www.cnblogs.com/jiang2538406936/p/5750004.html