android日期选择器

不用在界面中添加任何的标签,直接在要显示时间的地方进行点击事件,

Calendar calendar  = Calendar.getInstance();
final DatePickerDialog dialog = new DatePickerDialog(mContext,R.style.MyDatePickerDialogTheme, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//
}
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));

dialog.setButton(DialogInterface.BUTTON_POSITIVE, "取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog1, int which) {
int year = dialog.getDatePicker().getYear();
int month = dialog.getDatePicker().getMonth()+1;
int day = dialog.getDatePicker().getDayOfMonth();
String dateStr = year + "" + month + "" + day+"";
check_in_text.setText(dateStr);
}
});
dialog.show();
break;

这部分就是点击事件之后弹出的具体选择日期的标签页,同时也可以将具体的选择之后的时间进行赋值展示,

不过要注意时间中月份的赋值,该部分比较特殊,需要理解,获取到的月份比实际的要小1,

针对不同的Android手机来说,主题颜色不一致,针对的对应的界面颜色也是不一致的,为了统一主题背景我们在values文件夹下的style.xml文件中添加一下主题背景
 pasting

<!--用于日历标签主题背景色-->
<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
<item name="android:colorAccent">@color/color_bg_selected</item>
</style>
选取相应的背景颜色,最后实现多个手机之间的共通,
下面是针对日期选择器选择的时间,进行确认,最终的两个时间节点之间的天数是几天,为了一致我们进行了如下的计算方法
Intent intent = new Intent(mContext,OrderHotelActivity.class);
intent.putExtra("hotelHouse" , data.get(position));
intent.putExtra("hotelTitle" , hotelBean.getTitle());
//判断具体的入住天数
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf= new SimpleDateFormat("yyyyMMdd");
try {
Date start = sdf.parse(check_in_text.getText().toString());
Date end = sdf.parse(check_out_text.getText().toString());
cal.setTime(start);
long time1 = cal.getTimeInMillis();
cal.setTime(end);
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
intent.putExtra("bookTime" , check_in_text.getText()+"-"+check_out_text.getText()+" "+Integer.parseInt(String.valueOf(between_days))+"");
intent.putExtra("bookTimeNum" , 1);
if(CommonUtils.getUserInfo(mContext) == null){
intent = new Intent(mContext,LoginActivity.class);
intent.putExtra("from" , TAG);
intent.putExtra("objId" , id);
}
startActivity(intent);
} catch (ParseException e) {
e.printStackTrace();
}
最终的版本是成功的,要注意的就是日期选择器显示的时候,有可能会因为主题原因导致确定和取消按钮不显示,所以要在后面设置主题样式


posted @ 2018-12-24 16:27  轩钰儿  阅读(2597)  评论(0编辑  收藏  举报