你的位置:首页 > 操作系统

[操作系统]日期对话框(DatePickerDialog)和时间对话框(TimePickerDialog)

  • 效果图

  •  布局
<Button  android:id="@+id/btn_date"  android:text="弹出日期选择对话框"  android:layout_width="0dp"  android:layout_weight="1"  android:layout_height="wrap_content" /> <Button  android:id="@+id/btn_time"  android:text="弹出时间选择对话框"  android:layout_width="0dp"  android:layout_weight="1"  android:layout_height="wrap_content" />

 

 
  • 代码
   
package com.chase.datetimedialog;import android.app.DatePickerDialog;import android.app.DatePickerDialog.OnDateSetListener;import android.app.TimePickerDialog;import android.app.TimePickerDialog.OnTimeSetListener;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 mBtnDate; private Button mBtnTime; @Override protected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.activity_main);  mBtnDate = (Button) findViewById(R.id.btn_date);  mBtnTime = (Button) findViewById(R.id.btn_time);  initDialog(); } private void initDialog() {  /**   * 弹出日期选择对话框   */  mBtnDate.setOnClickListener(new View.OnClickListener() {   @Override   public void onClick(View v) {    Calendar c = Calendar.getInstance();    int year=c.get(Calendar.YEAR);    int month=c.get(Calendar.MONTH);    final int day=c.get(Calendar.DAY_OF_MONTH);    DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, new OnDateSetListener() {     @Override     public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {      Toast.makeText(MainActivity.this,year+"年"+(month+1)+"月"+dayOfMonth+"日",Toast.LENGTH_SHORT).show();     }    },year,month,day);    datePickerDialog.show();   }  });  /**   * 弹出时间选择对话框   */  mBtnTime.setOnClickListener(new View.OnClickListener() {   @Override   public void onClick(View v) {    //获取当前系统时间     Calendar c = Calendar.getInstance();    int hour=c.get(Calendar.HOUR_OF_DAY);    int minute=c.get(Calendar.MINUTE);    //弹出时间对话框     TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this, new OnTimeSetListener() {     @Override     public void onTimeSet(TimePicker view, int hourOfDay, int minute) {      Toast.makeText(MainActivity.this,"时间 "+hourOfDay+":"+minute,Toast.LENGTH_SHORT).show();     }    }, hour, minute,true);    timePickerDialog.show();   }  }); }}

 

     



来自为知笔记(Wiz)