DatePicker日期滚动选择使用详解
更新时间:2022年09月05日 15:00:58 作者:芒果蜜桃π
这篇文章主要为大家详细介绍了DatePicker日期滚动选择的使用方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了DatePicker日期滚动选择的使用,供大家参考,具体内容如下
效果图为:
1.dialog_date.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:background="@color/background"> <TextView android:id="@+id/tv_cancle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:gravity="center" android:padding="10dp" android:layout_weight="1" android:text="@string/cancle" android:textColor="@color/colorBlack" android:textSize="16sp" /> <TextView android:layout_weight="3" android:gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /> <TextView android:id="@+id/tv_ok" android:layout_weight="1" android:gravity="center" android:padding="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:text="@string/commit" android:textColor="@color/colorBlack" android:textSize="16sp" /> </LinearLayout> <DatePicker android:id="@+id/datepicker" android:datePickerMode="spinner" android:calendarViewShown="false" android:startYear="2017" android:endYear="2020" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
布局里看起来还不是滚动式的,但所有工作弄完后,就是滚动啦
2.对应的MyDatePicker类:
public class MyDatePicker implements DatePicker.OnDateChangedListener, TimePicker.OnTimeChangedListener { /** * 定义结果回调接口 */ public interface ResultHandler { void handle(String time); } private DatePicker datePicker; private TextView tv_ok; private TextView tv_cancle; private ResultHandler handler; private String dateTime; private Context context; private String initDateTime; private Dialog datePickerDialog; public MyDatePicker(Context context, ResultHandler resultHandler, String initDateTime) { this.context = context; this.handler = resultHandler; this.initDateTime = initDateTime; initDialog(); } private void initDialog() { if (datePickerDialog == null) { datePickerDialog = new Dialog(context, R.style.mytime_dialog); // datePickerDialog = new Dialog(context); datePickerDialog.setCancelable(false); datePickerDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); datePickerDialog.setContentView(R.layout.dialog_date); Window window = datePickerDialog.getWindow(); window.setGravity(Gravity.BOTTOM); window.setWindowAnimations(R.style.dialogWindowAnim); //设置窗口弹出动画 WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics dm = new DisplayMetrics(); manager.getDefaultDisplay().getMetrics(dm); WindowManager.LayoutParams lp = window.getAttributes(); lp.width = dm.widthPixels; window.setAttributes(lp); } initView(); } private void initView() { datePicker = (DatePicker) datePickerDialog.findViewById(R.id.datepicker); tv_ok = (TextView) datePickerDialog.findViewById(R.id.tv_ok); tv_cancle = (TextView) datePickerDialog.findViewById(R.id.tv_cancle); tv_cancle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { datePickerDialog.dismiss(); } }); tv_ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { handler.handle( dateTime ); datePickerDialog.dismiss(); } }); datePickerDialog.show(); initDate(datePicker); } public void initDate(DatePicker datePicker) { Calendar calendar = Calendar.getInstance(); if (!(null == initDateTime || "".equals(initDateTime))) { calendar = this.getCalendarByInintData(initDateTime); } else { initDateTime = calendar.get(Calendar.YEAR) + "年" + calendar.get(Calendar.MONTH) + "月" + calendar.get(Calendar.DAY_OF_MONTH) + "日 " + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE); } datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), this); } /** * 实现将初始日期时间2012年07月02日 16:45 拆分成年 月 日 时 分 秒,并赋值给calendar * * @param initDateTime * 初始日期时间值 字符串型 * @return Calendar */ private Calendar getCalendarByInintData(String initDateTime) { Calendar calendar = Calendar.getInstance(); // 将初始日期时间2012年07月02日 16:45 拆分成年 月 日 时 分 秒 String date = spliteString(initDateTime, "日", "index", "front"); // 日期 String time = spliteString(initDateTime, "日", "index", "back"); // 时间 String yearStr = spliteString(date, "年", "index", "front"); // 年份 String monthAndDay = spliteString(date, "年", "index", "back"); // 月日 String monthStr = spliteString(monthAndDay, "月", "index", "front"); // 月 String dayStr = spliteString(monthAndDay, "月", "index", "back"); // 日 String hourStr = spliteString(time, ":", "index", "front"); // 时 String minuteStr = spliteString(time, ":", "index", "back"); // 分 int currentYear = Integer.valueOf(yearStr.trim()).intValue(); int currentMonth = Integer.valueOf(monthStr.trim()).intValue() - 1; int currentDay = Integer.valueOf(dayStr.trim()).intValue(); int currentHour = Integer.valueOf(hourStr.trim()).intValue(); int currentMinute = Integer.valueOf(minuteStr.trim()).intValue(); calendar.set(currentYear, currentMonth, currentDay, currentHour, currentMinute); return calendar; } /** * 截取子串 * * @param srcStr * 源串 * @param pattern * 匹配模式 * @param indexOrLast * @param frontOrBack * @return */ public static String spliteString(String srcStr, String pattern, String indexOrLast, String frontOrBack) { String result = ""; int loc = -1; if (indexOrLast.equalsIgnoreCase("index")) { loc = srcStr.indexOf(pattern); // 取得字符串第一次出现的位置 } else { loc = srcStr.lastIndexOf(pattern); // 最后一个匹配串的位置 } if (frontOrBack.equalsIgnoreCase("front")) { if (loc != -1) result = srcStr.substring(0, loc); // 截取子串 } else { if (loc != -1) result = srcStr.substring(loc + 1, srcStr.length()); // 截取子串 } return result; } @Override public void onDateChanged(DatePicker datePicker, int i, int i1, int i2) { // 获得日历实例 Calendar calendar = Calendar.getInstance(); calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日"); dateTime = sdf.format(calendar.getTime()); } @Override public void onTimeChanged(TimePicker timePicker, int i, int i1) { onDateChanged(null, 0, 0, 0); } }
设置对话框样式,核心代码:
private void initDialog() { if (datePickerDialog == null) { datePickerDialog = new Dialog(context, R.style.mytime_dialog); // datePickerDialog = new Dialog(context); datePickerDialog.setCancelable(false); datePickerDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); datePickerDialog.setContentView(R.layout.dialog_date); Window window = datePickerDialog.getWindow(); window.setGravity(Gravity.BOTTOM);//使对话框出现在底部 window.setWindowAnimations(R.style.dialogWindowAnim); //设置窗口弹出动画 WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics dm = new DisplayMetrics(); manager.getDefaultDisplay().getMetrics(dm); WindowManager.LayoutParams lp = window.getAttributes(); lp.width = dm.widthPixels; window.setAttributes(lp); } initView(); }
定义对话框style风格和添加动画:
<style name="mytime_dialog" parent="Theme.AppCompat.Light.NoActionBar"> <item name="android:windowFrame">@null</item> <item name="android:windowNoTitle">true</item> <item name="android:windowIsFloating">true</item> <item name="android:windowContentOverlay">@null</item> <item name="android:windowBackground">@color/background</item> </style> <style name="dialogWindowAnim" parent="android:Animation" mce_bogus="1"> <item name="android:windowEnterAnimation">@anim/dialog_enter_anim</item> <item name="android:windowExitAnimation">@anim/dialog_exit_anim</item> </style>
dialog_enter_anim.xml的代码:
<?xml version="1.0" encoding="utf-8"?> <!-- 弹出时动画 --> <set xmlns:android="http://schemas.android.com/apk/res/android"> <scale android:interpolator="@android:anim/accelerate_interpolator" android:fromXScale="1.0" android:toXScale="1.0" android:fromYScale="0.0" android:toYScale="1.0" android:pivotX="0%" android:pivotY="100%" android:fillAfter="false" android:duration="400"/> </set>
dialog_exit_anim.xml的代码:
<?xml version="1.0" encoding="utf-8"?> <!-- 退出时动画效果 --> <set xmlns:android="http://schemas.android.com/apk/res/android"> <scale android:interpolator="@android:anim/accelerate_interpolator" android:fromXScale="1.0" android:toXScale="1.0" android:fromYScale="1.0" android:toYScale="0.0" android:pivotX="0%" android:pivotY="100%" android:fillAfter="false" android:duration="400"/> </set>
3.在主界面activity中需要使用日期对话框的地方,调用函数initMyDatePicker()即可:
private void initMyDatePicker() { SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");//格式为 2013年9月3日 14:44 Date curDate = new Date(System.currentTimeMillis());//获取当前时间 String currentDate = formatter.format(curDate); myDatePicker = new MyDatePicker(this, new MyDatePicker.ResultHandler() { @Override public void handle(String time) { tv_showCurrentDate1.setText(time ); } },currentDate); }
注:DatePicker的样式会受主题的样式影响,写的时候弄了好久,一定要注意才行
<style name="mytime_dialog" parent="Theme.AppCompat.Light.NoActionBar"> <item name="android:windowFrame">@null</item> <item name="android:windowNoTitle">true</item> <item name="android:windowIsFloating">true</item> <item name="android:windowContentOverlay">@null</item> <item name="android:windowBackground">@color/background</item> </style>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Android消息推送:手把手教你集成小米推送(附demo)
本篇文章主要介绍了Android消息推送:手把手教你集成小米推送,非常具有实用价值,需要的朋友可以参考下。2016-12-12flutter BottomAppBar实现不规则底部导航栏
这篇文章主要为大家详细介绍了flutter BottomAppBar实现不规则底部导航栏,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2019-07-07
最新评论