網站首頁 編程語言 正文
本文實例為大家分享了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>
原文鏈接:https://blog.csdn.net/An_nAl/article/details/77069472
相關推薦
- 2023-01-21 RecyclerBezierChart曲線圖表繪制_Android
- 2022-04-01 FastDFS服務不能上傳文件 報錯:fileutil.MyException: getStoreS
- 2022-02-17 uni-app的 tabBar添加陰影
- 2022-12-26 C++?Boost?log日志庫超詳細講解_C 語言
- 2022-12-21 redis?setIfAbsent返回null的問題及解決_Redis
- 2023-01-10 Flutter圖片緩存管理ImageCache原理分析_Android
- 2023-05-30 C++中map和set的使用詳細攻略_C 語言
- 2022-03-14 surface屏幕自動調節亮度無法關閉
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支