vsmy97datepicker怎么用datepicker

[android] 解决DatePickerDialog和TimePickerDialog控件取消按钮问题
一. 问题提出
在Android程序中,我们通常需要使用DatePicker来设置日期,TimePicker来设置时间。其基本步骤是:
1.先定义DatePicker和TimePicker布局
2.然后通过Calendar类获得系统时间
3.接着通过init方法将日期传递给DatePicker初始化日期控件
4.在响应点击事件中可以通过DatePicker的getYear()、getDayOfMonth()、getMonth()函数获取具体日期
同时可以在OnDateChangedListener事件中监听日期变化,设置时间函数方法同理。但是使用DatePickerDialog或TimePickerDialog控件时会遇到的一个问题,它就是android版本4.0后没有取消(Cancel)按钮,同时点击界面任何部分都能获取日期或时间,据说它是版本存在的BUG。对比图如下所示:
但是我们期待的效果如下图所示:
我采取的解决方法是通过自定义XML布局,经过DatePicker和TimePicker控件实现,同时在AlertDialog中设置取消按钮和确定按钮,通过函数setNegativeButton()和setPositiveButton()实现。
二. 简单实现日期和时间控件
简单实现方法非常简单,不需要设置日期或时间的XML布局,直接通过new DatePickerDialog或TimePickerDialog即可实现。代码如下:
//点击日期按钮布局 设置日期
layoutDate.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int month, int day) {
// TODO Auto-generated method stub
//更新EditText控件日期 小于10加0
dateEdit.setText(new StringBuilder().append(mYear).append(-)
.append((mMonth + 1) & 10 ? 0 + (mMonth + 1) : (mMonth + 1))
.append(-)
.append((mDay & 10) ? 0 + mDay : mDay) );
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH) ).show();
其中mYear、mMonth、mDay是定义变量,同时dateEdit是一个EditText控件用于显示具体日期,当数字小于10时前补0,如。下面是设置时间,显示效果和第三部分的效果相同。
//点击时间按钮布局 设置时间
layoutTime.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new TimePickerDialog(MainActivity.this,
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hour, int minute) {
// TODO Auto-generated method stub
//更新EditText控件时间 小于10加0
timeEdit.setText(new StringBuilder()
.append(mHour & 10 ? 0 + mHour : mHour).append(:)
.append(mMinute & 10 ? 0 + mMinute : mMinute).append(:00) );
}, calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE), true).show();
三. 自定义布局实现
下面是自定义布局实现,而且我自认为该界面布局非常好看,这也是我&随手拍&项目自己最后总结出来的一个比较欣赏的界面吧!希望你也喜欢,效果如下:
如图所示,界面中日期、时间EditText不可编辑,需要通过点击底部布局来设置。同时备注信息的EditText通过自定义背景实现,设置日期、时间中有取消按钮。
1.项目结构如下图所示
2.activity_main.xml布局文件
3.date_dialog.xml文件:日期控件布局
4.time_dialog.xml文件:时间控件布局
5.drawable-hdpi中editview_shape.xml文件 实现自定义EditText控件格式
6.MainActivity.java
public class MainActivity extends Activity {
//自定义变量
private EditText titleE
private EditText dateE
private EditText timeE
private EditText contentE
//底部四个布局按钮
private LinearLayout layoutD
private LinearLayout layoutT
private LinearLayout layoutC
private LinearLayout layoutS
//定义显示时间控件
private C //通过Calendar获取系统时间
private int mY
private int mM
private int mD
private int mH
private int mM
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//锁定屏幕
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
//获取对象
titleEdit = (EditText) findViewById(R.id.showtitle);
dateEdit = (EditText) findViewById(R.id.showdate);
timeEdit = (EditText) findViewById(R.id.showtime);
contentEdit = (EditText) findViewById(R.id.editText1);
layoutDate = (LinearLayout) findViewById(R.id.layout_date);
layoutTime = (LinearLayout) findViewById(R.id.layout_time);
layoutCancel = (LinearLayout) findViewById(R.id.layout_cancel);
layoutSave = (LinearLayout) findViewById(R.id.layout_save);
calendar = Calendar.getInstance();
//点击日期按钮布局 设置日期
layoutDate.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//通过自定义控件AlertDialog实现
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View view = (LinearLayout) getLayoutInflater().inflate(R.layout.date_dialog, null);
final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
//设置日期简略显示 否则详细显示 包括:星期周
datePicker.setCalendarViewShown(false);
//初始化当前日期
calendar.setTimeInMillis(System.currentTimeMillis());
datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH), null);
//设置date布局
builder.setView(view);
builder.setTitle(设置日期信息);
builder.setPositiveButton(确
定, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//日期格式
StringBuffer sb = new StringBuffer();
sb.append(String.format(%d-%02d-%02d,
datePicker.getYear(),
datePicker.getMonth() + 1,
datePicker.getDayOfMonth()));
dateEdit.setText(sb);
//赋值后面闹钟使用
mYear = datePicker.getYear();
mMonth = datePicker.getMonth();
mDay = datePicker.getDayOfMonth();
dialog.cancel();
builder.setNegativeButton(取
消, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
builder.create().show();
layoutDate.setOnTouchListener(new OnTouchListener() { //设置布局背景
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
layoutDate.setBackgroundColor(Color.WHITE);
layoutTime.setBackgroundColor(Color.TRANSPARENT);
layoutCancel.setBackgroundColor(Color.TRANSPARENT);
layoutSave.setBackgroundColor(Color.TRANSPARENT);
//点击时间按钮布局 设置时间
layoutTime.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//自定义控件
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View view = (LinearLayout) getLayoutInflater().inflate(R.layout.time_dialog, null);
final TimePicker timePicker = (TimePicker) view.findViewById(R.id.time_picker);
//初始化时间
calendar.setTimeInMillis(System.currentTimeMillis());
timePicker.setIs24HourView(true);
timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY));
timePicker.setCurrentMinute(Calendar.MINUTE);
//设置time布局
builder.setView(view);
builder.setTitle(设置时间信息);
builder.setPositiveButton(确
定, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mHour = timePicker.getCurrentHour();
mMinute = timePicker.getCurrentMinute();
//时间小于10的数字 前面补0 如01:12:00
timeEdit.setText(new StringBuilder().append(mHour & 10 ? 0 + mHour : mHour).append(:)
.append(mMinute & 10 ? 0 + mMinute : mMinute).append(:00) );
dialog.cancel();
builder.setNegativeButton(取
消, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
builder.create().show();
layoutTime.setOnTouchListener(new OnTouchListener() { //设置布局背景
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
layoutDate.setBackgroundColor(Color.TRANSPARENT);
layoutTime.setBackgroundColor(Color.WHITE);
layoutCancel.setBackgroundColor(Color.TRANSPARENT);
layoutSave.setBackgroundColor(Color.TRANSPARENT);
//点击取消按钮
layoutCancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dateEdit.setText();
dateEdit.setHint();
timeEdit.setText();
timeEdit.setHint(00:00:00);
contentEdit.setText();
contentEdit.setHint(记录旅途中的备注信息...);
layoutCancel.setOnTouchListener(new OnTouchListener() { //设置布局背景
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
layoutDate.setBackgroundColor(Color.TRANSPARENT);
layoutTime.setBackgroundColor(Color.TRANSPARENT);
layoutCancel.setBackgroundColor(Color.WHITE);
layoutSave.setBackgroundColor(Color.TRANSPARENT);
//点击保存按钮
layoutSave.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//确认保存按钮
new AlertDialog.Builder(MainActivity.this).setTitle(确认保存吗?)
.setIcon(android.R.drawable.ic_dialog_info)
.setPositiveButton(确
定, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
* 插入操作
.setNegativeButton(返
回, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}).show();
layoutSave.setOnTouchListener(new OnTouchListener() { //设置布局背景
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
layoutDate.setBackgroundColor(Color.TRANSPARENT);
layoutTime.setBackgroundColor(Color.TRANSPARENT);
layoutCancel.setBackgroundColor(Color.TRANSPARENT);
layoutSave.setBackgroundColor(Color.WHITE);
} // End onCreate
最后希望文章对大家有所帮助!如果你知道我这篇文章想要阐述的内容是什么?为什么要写这篇文章?或许它会对你有所帮助,一方面是布局可能对你有启发;另一方面就是刚好遇到那个问题的同学。
在点击&保存&按钮时,也可把数据存储至数据库中调用MySQLiteOpenHelper,这里就不再介绍。写着写着就到了凌晨5点了,程序猿生活还是要改下啊~自己保重自己的身体吧!期待改正自己的作息,难难难~
(window.slotbydup=window.slotbydup || []).push({
id: '2467140',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467141',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467143',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467148',
container: s,
size: '1000,90',
display: 'inlay-fix'Date Range Picker
A JavaScript component for choosing date ranges.
Designed to work with the Bootstrap CSS framework.
Originally built for reporting at ,
the Date Range Picker can be attached to any webpage element to pop up two calendars
for selecting dates, times, or from predefined ranges like "Last 30 Days".
Date Range Picker relies on ,
Include the required scripts and stylesheet in your page:
Then attach the picker to the element you want to trigger it:
You can customize Date Range Picker with , and
get notified when the user chooses new dates by providing a callback function.
Date Range Picker
The Date Range Picker is attached to a text input. It will use the current
value of the input to initialize, and update the input if new dates are chosen.
Date and Time
The Date Range Picker can also be used to select times. Hour, minute and (optional)
second dropdowns are added below the calendars. An option exists to set the increment
count of the minutes dropdown to e.g. offer only 15-minute or 30-minute increments.
Single Date Picker
The Date Range Picker can be turned into a single date picker widget with only
one calendar. In this example, dropdowns to select a month and year have also
been enabled at the top of the calendar to quickly jump to different months.
Predefined Ranges
This example shows the option to predefine date ranges that
the user can choose from a list.
Input Initially Empty
If you're using a date range as a filter, you may want to attach a picker to an
input but leave it empty by default. This example shows how to accomplish that
using the autoUpdateInput setting, and the apply and
cancel events.
Configuration Generator
singleDatePicker
showDropdowns
showWeekNumbers
showISOWeekNumbers
timePicker
timePicker24Hour
timePickerIncrement (in minutes)
timePickerSeconds
dateLimit (with example date range span)
ranges (with example predefined ranges)
locale (with example settings)
linkedCalendars
autoUpdateInput
alwaysShowCalendars
buttonClasses
applyClass
cancelClass
Your Date Range Picker
Configuration
startDate (Date object, moment object or string) The start of the initially selected date range
endDate: (Date object, moment object or string) The end of the initially selected date range
minDate: (Date object, moment object or string) The earliest date a user may select
maxDate: (Date object, moment object or string) The latest date a user may select
dateLimit: (object) The maximum span between the selected start and end dates. Can have any property you can add to a moment object (i.e. days, months)
showDropdowns: (boolean) Show year and month select boxes above calendars to jump to a specific month and year
showWeekNumbers: (boolean) Show localized week numbers at the start of each week on the calendars
showWeekNumbers: (boolean) Show ISO week numbers at the start of each week on the calendars
timePicker: (boolean) Allow selection of dates with times, not just dates
timePickerIncrement: (number) Increment of the minutes selection list for times (i.e. 30 to allow only selection of times ending in 0 or 30)
timePicker24Hour: (boolean) Use 24-hour instead of 12-hour times, removing the AM/PM selection
timePickerSeconds: (boolean) Show seconds in the timePicker
ranges: (object) Set predefined date ranges the user can select from. Each key is the label for the range, and its value an array with two dates representing the bounds of the range
opens: (string: 'left'/'right'/'center') Whether the picker appears aligned to the left, to the right, or centered under the HTML element it's attached to
drops: (string: 'down' or 'up') Whether the picker appears below (default) or above the HTML element it's attached to
buttonClasses: (array) CSS class names that will be added to all buttons in the picker
applyClass: (string) CSS class string that will be added to the apply button
cancelClass: (string) CSS class string that will be added to the cancel button
locale: (object) Allows you to provide localized strings for buttons and labels, customize the date display format, and change the first day of week for the calendars
singleDatePicker: (boolean) Show only a single calendar to choose one date, instead of a range picke the start and end dates provided to your callback will be the same single date chosen
autoApply: (boolean) Hide the apply and cancel buttons, and automatically apply a new date range as soon as two dates or a predefined range is selected
linkedCalendars: (boolean) When enabled, the two calendars displayed will always be for two sequential months (i.e. January and February), and both will be advanced when clicking the left or right arrows above the calendars. When disabled, the two calendars can be individually advanced and display any month/year.
parentEl: (string) jQuery selector of the parent element that the date range picker will be added to, if not provided this will be 'body'
isInvalidDate: (function) A function that is passed each date in the two
calendars before they are displayed, and may return true or false to indicate whether
that date should be available for selection or not.
autoUpdateInput: (boolean) Indicates whether the date range picker should
automatically update the value of an &input& element it's attached to
at initialization and when the selected dates change.
alwaysShowCalendars: (boolean) Normally, if you use the ranges
option to specify pre-defined date ranges, calendars for choosing a custom date range are not shown until the user clicks "Custom Range". When this option is set to true, the calendars for choosing a custom date range are always shown instead.
You can programmatically update the startDate and endDate
in the picker using the setStartDate and setEndDate methods.
You can access the Date Range Picker object and its functions and properties through
data properties of the element you attached it to.
setStartDate(Date/moment/string): Sets the date range picker's currently selected start date to the provided date
setEndDate(Date/moment/string): Sets the date range picker's currently selected end date to the provided date
Example usage:
Several events are triggered on the element you attach the picker to, which you can listen for.
show.daterangepicker: Triggered when the picker is shown
hide.daterangepicker: Triggered when the picker is hidden
showCalendar.daterangepicker: Triggered when the calendar(s) are shown
hideCalendar.daterangepicker: Triggered when the calendar(s) are hidden
apply.daterangepicker: Triggered when the apply button is clicked,
or when a predefined range is clicked
cancel.daterangepicker: Triggered when the cancel button is clicked
Some applications need a "clear" instead of a "cancel" functionality, which can be achieved by changing the button label and watching for the cancel event:
While passing in a callback to the constructor is the easiest way to listen for changes in the selected date range, you can also do something every time the apply button is clicked even if the selection hasn't changed:
The MIT License (MIT)
Copyright (c)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Please enable JavaScript to view the&&&&wpf DatePicker扩展 增加 选择今天 和 清空功能 源码
wpf DatePicker 无清空功能和选择今天功能,现在通过继承DatePicker类实现,可以根据当前 自由的扩展功能。
若举报审核通过,可奖励20下载分
被举报人:
peng13nannan
举报的资源分:
请选择类型
资源无法下载
资源无法使用
标题与实际内容不符
含有危害国家安全内容
含有反动色情等内容
含广告内容
版权问题,侵犯个人或公司的版权
*详细原因:
VIP下载&&免积分60元/年(1200次)
您可能还需要
开发技术下载排行DatePicker/TimePicker与init(.)和setOnTimeChangedListener(.)
DatePicker/TimePicker与init(.)和setOnTimeChangedListener(.)
查看次数14768 发表时间 06:36:36
&LinearLayout xmlns:android=&/apk/res/android&
xmlns:tools=&/tools&
android:id=&@+id/LinearLayout1& ...
&LinearLayout xmlns:android=&/apk/res/android&
xmlns:tools=&/tools&
android:id=&@+id/LinearLayout1&
android:layout_width=&match_parent&
android:layout_height=&match_parent&
android:orientation=&vertical&
android:paddingBottom=&@dimen/activity_vertical_margin&
android:paddingLeft=&@dimen/activity_horizontal_margin&
android:paddingRight=&@dimen/activity_horizontal_margin&
android:paddingTop=&@dimen/activity_vertical_margin&
tools:context=&.MainActivity& &
android:id=&@+id/edt&
android:layout_width=&wrap_content&
android:layout_height=&wrap_content&
&LinearLayout
android:layout_width=&wrap_content&
android:layout_height=&wrap_content&
android:orientation=&horizontal&&
&DatePicker
android:id=&@+id/date&
android:layout_width=&wrap_content&
android:layout_height=&wrap_content&/&
&TimePicker
android:id=&@+id/time&
android:layout_width=&wrap_content&
android:layout_height=&wrap_content&/&
&/LinearLayout&
&/LinearLayout&
package com.xyb.d
import android.os.B
import android.app.A
import android.text.method.DateTimeKeyL
import android.view.M
import android.widget.DateP
import android.widget.DatePicker.OnDateChangedL
import android.widget.EditT
import android.widget.TimeP
import android.widget.TimePicker.OnTimeChangedL
public class MainActivity extends Activity {
//////////////////////////////////////////////////////////////////////////////////////////
private EditText showview=
private DatePicker date=
private TimePicker time=
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
this.showview=(EditText)super.findViewById(R.id.edt);
this.date=(DatePicker)super.findViewById(R.id.date);
this.time=(TimePicker)super.findViewById(R.id.time);
this.time.setIs24HourView(true);//时间设置为24小时制
this.date.init(MainActivity.this.date.getYear(),MainActivity.this.date.getMonth()//设置日期监听器
, MainActivity.this.date.getDayOfMonth(),new onDateChangedListenerImp1());
this.time.setOnTimeChangedListener(new onTimeChangedListenerImp1());//设置时间监听器
setdatetime();
private class onDateChangedListenerImp1 implements OnDateChangedListener{
public void onDateChanged(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
setdatetime();
private class onTimeChangedListenerImp1 implements OnTimeChangedListener{
public void onTimeChanged(TimePicker arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
setdatetime();
//在文本中显示日期时间
public void setdatetime(){
MainActivity.this.showview.setText(MainActivity.this.date.getYear()+&-&+
(MainActivity.this.date.getMonth()+1)+&-&+MainActivity.this.date.getDayOfMonth()+&-&
+MainActivity.this.time.getCurrentHour()+&-&+MainActivity.this.time.getCurrentMinute());
/////////////////////////////////////////////////////////////////////////////////////////////////////////
public boolean onCreateOptionsMenu(Menu menu) {
// I this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
(转发请注明转自:)
&&相关推荐
&&&&&&( 20:36:32)
&&&&&&( 20:36:32)
&&&&&&( 20:36:33)
&&&&&&( 20:36:33)
&&&&&&( 07:36:32)
&&&&&&( 06:36:36)
&&&&&&( 06:36:36)
&&&&&&( 06:36:35)
&&&&&&( 06:36:34)
&&&&&&( 06:36:33)
&&发表评论
(不超过20个字符或10个汉字)
最新发布...
最新推荐...
浏览最多...
点击:130357
点击:122131
点击:108454
点击:89270
点击:84574
点击:72692
点击:71105
点击:70078
点击:65035
点击:61362

我要回帖

更多关于 my97datepicker怎么用 的文章

 

随机推荐