欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

轻松实现可扩展自定义的Android滚轮时间选择控件

程序员文章站 2024-03-04 17:42:05
项目需求中有个功能模块需要用到时间选择控件,但是android系统自带的太丑了,只能自己优化下,结合wheelview实现滚轮选择日期,好像网上也挺多这种文章的。但是适用范...

项目需求中有个功能模块需要用到时间选择控件,但是android系统自带的太丑了,只能自己优化下,结合wheelview实现滚轮选择日期,好像网上也挺多这种文章的。但是适用范围还是不同,希望这个能够对需求相同的朋友有一定帮助。控件标题还有年月日时分秒这些可以自己控制是否显示,先来看效果。 

1.有年月日时分的开始时间

轻松实现可扩展自定义的Android滚轮时间选择控件

2.只有年月日的结束时间

轻松实现可扩展自定义的Android滚轮时间选择控件

3.用于有时身份证到期的时间选择(分为勾选长期和直接选择时间两种,另外长期后面自己也可以进行扩展)

轻松实现可扩展自定义的Android滚轮时间选择控件

4.项目结构

轻松实现可扩展自定义的Android滚轮时间选择控件

5.直接贴代码,代码里面注释很详细

 <span style="font-size:18px;"><span style="font-size:14px;">package com.andrew.datechoosewheelviewdemo;


import android.app.activity;
import android.app.dialog;
import android.content.context;
import android.os.looper;
import android.view.layoutinflater;
import android.view.view;
import android.view.viewgroup;
import android.widget.button;
import android.widget.linearlayout;
import android.widget.textview;

import com.andrew.datechoosewheelviewdemo.widget.onwheelchangedlistener;
import com.andrew.datechoosewheelviewdemo.widget.onwheelscrolllistener;
import com.andrew.datechoosewheelviewdemo.widget.wheelview;
import com.andrew.datechoosewheelviewdemo.widget.adapters.abstractwheeltextadapter;

import java.util.arraylist;
import java.util.calendar;

/**
 * 使用说明:1.showlongterm()是否显示长期选项
 * 2.settimepickergone隐藏时间选择
 * 3.接口datechooseinterface
 *
 * 用于时间日期的选择
 * created by liuhongxia on 2016/4/16.
 */
public class datechoosewheelviewdialog extends dialog implements view.onclicklistener {
 //控件
 private wheelview myearwheelview;
 private wheelview mdatewheelview;
 private wheelview mhourwheelview;
 private wheelview mminutewheelview;
 private calendartextadapter mdateadapter;
 private calendartextadapter mhouradapter;
 private calendartextadapter mminuteadapter;
 private calendartextadapter myearadapter;
 private textview mtitletextview;
 private button msurebutton;
 private dialog mdialog;
 private button mclosedialog;
 private linearlayout mlongtermlayout;
 private textview mlongtermtextview;

 //变量
 private arraylist<string> arry_date = new arraylist<string>();
 private arraylist<string> arry_hour = new arraylist<string>();
 private arraylist<string> arry_minute = new arraylist<string>();
 private arraylist<string> arry_year = new arraylist<string>();

 private int nowdateid = 0;
 private int nowhourid = 0;
 private int nowminuteid = 0;
 private int nowyearid = 0;
 private string myearstr;
 private string mdatestr;
 private string mhourstr;
 private string mminutestr;
 private boolean mblnbelongterm = false;//是否需要长期
 private boolean mblntimepickergone = false;//时间选择是否显示


 //常量
 private final int max_text_size = 18;
 private final int min_text_size = 16;

 private context mcontext;
 private datechooseinterface datechooseinterface;

 public datechoosewheelviewdialog(context context, datechooseinterface datechooseinterface) {
 super(context);
 this.mcontext = context;
 this.datechooseinterface = datechooseinterface;
 mdialog = new dialog(context,r.style.dialog);
 initview();
 initdata();
 }


 private void initdata() {
 inityear();
 initdate();
 inithour();
 initminute();
 initlistener();
 }

 /**
 * 初始化滚动监听事件
 */
 private void initlistener() {
 //年份*****************************
 myearwheelview.addchanginglistener(new onwheelchangedlistener() {

  @override
  public void onchanged(wheelview wheel, int oldvalue, int newvalue) {
  string currenttext = (string) myearadapter.getitemtext(wheel.getcurrentitem());
  settextviewstyle(currenttext, myearadapter);
  myearstr = arry_year.get(wheel.getcurrentitem()) + "";
  }
 });

 myearwheelview.addscrollinglistener(new onwheelscrolllistener() {

  @override
  public void onscrollingstarted(wheelview wheel) {

  }

  @override
  public void onscrollingfinished(wheelview wheel) {
  string currenttext = (string) myearadapter.getitemtext(wheel.getcurrentitem());
  settextviewstyle(currenttext, myearadapter);
  }
 });

 //日期********************
 mdatewheelview.addchanginglistener(new onwheelchangedlistener() {

  @override
  public void onchanged(wheelview wheel, int oldvalue, int newvalue) {
  string currenttext = (string) mdateadapter.getitemtext(wheel.getcurrentitem());
  settextviewstyle(currenttext, mdateadapter);
//  mdatecalendartextview.settext(" " + arry_date.get(wheel.getcurrentitem()));
  mdatestr = arry_date.get(wheel.getcurrentitem());
  }
 });

 mdatewheelview.addscrollinglistener(new onwheelscrolllistener() {

  @override
  public void onscrollingstarted(wheelview wheel) {

  }

  @override
  public void onscrollingfinished(wheelview wheel) {
  string currenttext = (string) mdateadapter.getitemtext(wheel.getcurrentitem());
  settextviewstyle(currenttext, mdateadapter);
  }
 });

 //小时***********************************
 mhourwheelview.addchanginglistener(new onwheelchangedlistener() {

  @override
  public void onchanged(wheelview wheel, int oldvalue, int newvalue) {
  string currenttext = (string) mhouradapter.getitemtext(wheel.getcurrentitem());
  settextviewstyle(currenttext, mhouradapter);
  mhourstr = arry_hour.get(wheel.getcurrentitem()) + "";
  }
 });

 mhourwheelview.addscrollinglistener(new onwheelscrolllistener() {

  @override
  public void onscrollingstarted(wheelview wheel) {

  }

  @override
  public void onscrollingfinished(wheelview wheel) {
  string currenttext = (string) mhouradapter.getitemtext(wheel.getcurrentitem());
  settextviewstyle(currenttext, mhouradapter);
  }
 });

 //分钟********************************************
 mminutewheelview.addchanginglistener(new onwheelchangedlistener() {

  @override
  public void onchanged(wheelview wheel, int oldvalue, int newvalue) {
  string currenttext = (string) mminuteadapter.getitemtext(wheel.getcurrentitem());
  settextviewstyle(currenttext, mminuteadapter);
  mminutestr = arry_minute.get(wheel.getcurrentitem()) + "";
  }
 });

 mminutewheelview.addscrollinglistener(new onwheelscrolllistener() {

  @override
  public void onscrollingstarted(wheelview wheel) {

  }

  @override
  public void onscrollingfinished(wheelview wheel) {
  string currenttext = (string) mminuteadapter.getitemtext(wheel.getcurrentitem());
  settextviewstyle(currenttext, mminuteadapter);
  }
 });
 }

 /**
 * 初始化分钟
 */
 private void initminute() {
 calendar nowcalendar = calendar.getinstance();
 int nowminite = nowcalendar.get(calendar.minute);
 arry_minute.clear();
 for (int i = 0; i <= 59; i++) {
  arry_minute.add(i + "");
  if (nowminite == i){
  nowminuteid = arry_minute.size() - 1;
  }
 }

 mminuteadapter = new calendartextadapter(mcontext, arry_minute, nowminuteid, max_text_size, min_text_size);
 mminutewheelview.setvisibleitems(5);
 mminutewheelview.setviewadapter(mminuteadapter);
 mminutewheelview.setcurrentitem(nowminuteid);
 mminutestr = arry_minute.get(nowminuteid) + "";
 settextviewstyle(mminutestr, mminuteadapter);

 }

 /**
 * 初始化时间
 */
 private void inithour() {
 calendar nowcalendar = calendar.getinstance();
 int nowhour = nowcalendar.get(calendar.hour_of_day);
 arry_hour.clear();
 for (int i = 0; i <= 23; i++) {
  arry_hour.add(i + "");
  if (nowhour == i){
  nowhourid = arry_hour.size() - 1;
  }
 }

 mhouradapter = new calendartextadapter(mcontext, arry_hour, nowhourid, max_text_size, min_text_size);
 mhourwheelview.setvisibleitems(5);
 mhourwheelview.setviewadapter(mhouradapter);
 mhourwheelview.setcurrentitem(nowhourid);
 mhourstr = arry_hour.get(nowhourid) + "";
 settextviewstyle(mhourstr, mhouradapter);
 }

 /**
 * 初始化年
 */
 private void inityear() {
 calendar nowcalendar = calendar.getinstance();
 int nowyear = nowcalendar.get(calendar.year);
 arry_year.clear();
 for (int i = 0; i <= 99; i++) {
  int year = nowyear -30 + i;
  arry_year.add(year + "年");
  if (nowyear == year) {
  nowyearid = arry_year.size() - 1;
  }
 }
 myearadapter = new calendartextadapter(mcontext, arry_year, nowyearid, max_text_size, min_text_size);
 myearwheelview.setvisibleitems(5);
 myearwheelview.setviewadapter(myearadapter);
 myearwheelview.setcurrentitem(nowyearid);
 myearstr = arry_year.get(nowyearid);
 }

 private void initview() {
 view view = layoutinflater.from(mcontext).inflate(r.layout.dialog_date_choose, null);
 mdialog.setcontentview(view);
 myearwheelview = (wheelview) view.findviewbyid(r.id.year_wv);
 mdatewheelview = (wheelview) view.findviewbyid(r.id.date_wv);
 mhourwheelview = (wheelview) view.findviewbyid(r.id.hour_wv);
 mminutewheelview = (wheelview) view.findviewbyid(r.id.minute_wv);
 mtitletextview = (textview) view.findviewbyid(r.id.title_tv);
 msurebutton = (button) view.findviewbyid(r.id.sure_btn);
 mclosedialog = (button) view.findviewbyid(r.id.date_choose_close_btn);
 mlongtermlayout = (linearlayout) view.findviewbyid(r.id.long_term_layout);
 mlongtermtextview = (textview) view.findviewbyid(r.id.long_term_tv);

 msurebutton.setonclicklistener(this);
 mclosedialog.setonclicklistener(this);
 mlongtermtextview.setonclicklistener(this);
 }

 /**
 * 初始化日期
 */
 private void initdate() {
 calendar nowcalendar = calendar.getinstance();
 int nowyear = nowcalendar.get(calendar.year);
 arry_date.clear();
 setdate(nowyear);
 mdateadapter = new calendartextadapter(mcontext, arry_date, nowdateid, max_text_size, min_text_size);
 mdatewheelview.setvisibleitems(5);
 mdatewheelview.setviewadapter(mdateadapter);
 mdatewheelview.setcurrentitem(nowdateid);

 mdatestr = arry_date.get(nowdateid);
 settextviewstyle(mdatestr, mdateadapter);
 }

 public void setdatedialogtitle(string title) {
 mtitletextview.settext(title);
 }

 public void settimepickergone(boolean isgone) {
 mblntimepickergone = isgone;
 if (isgone) {
  linearlayout.layoutparams yearparams = new linearlayout.layoutparams( linearlayout.layoutparams.wrap_content,
   linearlayout.layoutparams.wrap_content);
  yearparams.rightmargin = 22;

  linearlayout.layoutparams dateparams = new linearlayout.layoutparams( linearlayout.layoutparams.wrap_content,
   linearlayout.layoutparams.wrap_content);
  myearwheelview.setlayoutparams(yearparams);
  mdatewheelview.setlayoutparams(dateparams);

  mhourwheelview.setvisibility(view.gone);
  mminutewheelview.setvisibility(view.gone);
 } else {
  mhourwheelview.setvisibility(view.visible);
  mminutewheelview.setvisibility(view.visible);
 }

 }

 public void showlongterm(boolean show) {
 if (show) {
  mlongtermlayout.setvisibility(view.visible);
 } else {
  mlongtermlayout.setvisibility(view.gone);
 }

 }


 /**
 * 将改年的所有日期写入数组
 * @param year
 */
 private void setdate(int year){
 boolean isrun = isrunnian(year);
 calendar nowcalendar = calendar.getinstance();
 int nowmonth = nowcalendar.get(calendar.month) + 1;
 int nowday = nowcalendar.get(calendar.day_of_month);
 for (int month = 1; month <= 12; month++){
  switch (month){
  case 1:
  case 3:
  case 5:
  case 7:
  case 8:
  case 10:
  case 12:
   for (int day = 1; day <= 31; day++){
   arry_date.add(month + "月" + day + "日");

   if (month == nowmonth && day == nowday){
    nowdateid = arry_date.size() - 1;
   }
   }
   break;
  case 2:
   if (isrun){
   for (int day = 1; day <= 29; day++){
    arry_date.add(month + "月" + day + "日");
    if (month == nowmonth && day == nowday){
    nowdateid = arry_date.size() - 1;
    }
   }
   }else {
   for (int day = 1; day <= 28; day++){
    arry_date.add(month + "月" + day + "日");
    if (month == nowmonth && day == nowday){
    nowdateid = arry_date.size() - 1;
    }
   }
   }
   break;
  case 4:
  case 6:
  case 9:
  case 11:
   for (int day = 1; day <= 30; day++){
   arry_date.add(month + "月" + day + "日");
   if (month == nowmonth && day == nowday){
    nowdateid = arry_date.size() - 1;
   }
   }
   break;
  default:
   break;
  }
 }
 }

 /**
 * 判断是否是闰年
 * @param year
 * @return
 */
 private boolean isrunnian(int year){
 if(year % 4 == 0 && year % 100 !=0 || year % 400 == 0){
  return true;
 }else {
  return false;
 }
 }

 /**
 * 设置文字的大小
 * @param curriteitemtext
 * @param adapter
 */
 public void settextviewstyle(string curriteitemtext, calendartextadapter adapter) {
 arraylist<view> arraylist = adapter.gettestviews();
 int size = arraylist.size();
 string currenttext;
 for (int i = 0; i < size; i++) {
  textview textvew = (textview) arraylist.get(i);
  currenttext = textvew.gettext().tostring();
  if (curriteitemtext.equals(currenttext)) {
  textvew.settextsize(max_text_size);
  textvew.settextcolor(mcontext.getresources().getcolor(r.color.text_10));
  } else {
  textvew.settextsize(min_text_size);
  textvew.settextcolor(mcontext.getresources().getcolor(r.color.text_11));
  }
 }
 }

 @override
 public void onclick(view v) {
 switch (v.getid()) {
  case r.id.sure_btn://确定选择按钮监听
  if (mblntimepickergone) {
   datechooseinterface.getdatetime(strtimetodateformat(myearstr, mdatestr), mblnbelongterm);
  } else {
   datechooseinterface.getdatetime(strtimetodateformat(myearstr, mdatestr , mhourstr , mminutestr), mblnbelongterm);
  }
  dismissdialog();
  break;
  case r.id.date_choose_close_btn://关闭日期选择对话框
  dismissdialog();
  break;
  case r.id.long_term_tv://选择长期时间监听
  if (!mblnbelongterm) {
   mlongtermtextview.setbackgroundresource(r.drawable.gouxuanok);
   mblnbelongterm = true;
  } else {
   mlongtermtextview.setbackgroundresource(r.drawable.gouxuanno);
   mblnbelongterm = false;
  }
  default:
  break;
 }
 }

 /**
 * 对话框消失
 */
 private void dismissdialog() {

 if (looper.mylooper() != looper.getmainlooper()) {

  return;
 }

 if (null == mdialog || !mdialog.isshowing() || null == mcontext
  || ((activity) mcontext).isfinishing()) {

  return;
 }

 mdialog.dismiss();
 this.dismiss();
 }

 /**
 * 显示日期选择dialog
 */
 public void showdatechoosedialog() {

 if (looper.mylooper() != looper.getmainlooper()) {

  return;
 }

 if (null == mcontext || ((activity) mcontext).isfinishing()) {

  // 界面已被销毁
  return;
 }

 if (null != mdialog) {

  mdialog.show();
  return;
 }

 if (null == mdialog) {

  return;
 }

 mdialog.setcanceledontouchoutside(true);
 mdialog.show();
 }

 /**
 * xx年xx月xx日xx时xx分转成yyyy-mm-dd hh:mm
 * @param yearstr
 * @param datestr
 * @param hourstr
 * @param minutestr
 * @return
 */
 private string strtimetodateformat(string yearstr, string datestr, string hourstr, string minutestr) {

 return yearstr.replace("年", "-") + datestr.replace("月", "-").replace("日", " ")
  + hourstr + ":" + minutestr;
 }

 private string strtimetodateformat(string yearstr, string datestr) {

 return yearstr.replace("年", "-") + datestr.replace("月", "-").replace("日", "");
 }

 /**
 * 滚轮的adapter
 */
 private class calendartextadapter extends abstractwheeltextadapter {
 arraylist<string> list;

 protected calendartextadapter(context context, arraylist<string> list, int currentitem, int maxsize, int minsize) {
  super(context, r.layout.item_birth_year, r.id.tempvalue, currentitem, maxsize, minsize);
  this.list = list;
 }

 @override
 public view getitem(int index, view cachedview, viewgroup parent) {
  view view = super.getitem(index, cachedview, parent);
  return view;
 }

 @override
 public int getitemscount() {
  return list.size();
 }

 @override
 protected charsequence getitemtext(int index) {
  string str = list.get(index) + "";
  return str;
 }
 }

 /**
 * 回调选中的时间(默认时间格式"yyyy-mm-dd hh:mm:ss")
 */
 public interface datechooseinterface{
 void getdatetime(string time, boolean longtimechecked);
 }

}
</span></span>

 6.mainactivity里面使用

<span style="font-size:18px;"><span style="font-size:14px;">package com.andrew.datechoosewheelviewdemo;

import android.app.activity;
import android.os.bundle;
import android.view.view;
import android.widget.button;
import android.widget.textview;

public class mainactivity extends activity implements view.onclicklistener {
 private button mstartdatebutton;
 private button menddatebutton;
 private button mdatevalidbutton;
 private textview mshowcontenttextview;

 @override
 protected void oncreate(bundle savedinstancestate) {
 super.oncreate(savedinstancestate);
 setcontentview(r.layout.activity_main);

 mstartdatebutton = (button) this.findviewbyid(r.id.start_date_btn);
 menddatebutton = (button) this.findviewbyid(r.id.end_date_btn);
 mdatevalidbutton = (button) this.findviewbyid(r.id.date_valid_btn);
 mshowcontenttextview = (textview) this.findviewbyid(r.id.show_content_tv);

 mstartdatebutton.setonclicklistener(this);
 menddatebutton.setonclicklistener(this);
 mdatevalidbutton.setonclicklistener(this);
 }

 @override
 public void onclick(view v) {
 switch (v.getid()) {
  case r.id.start_date_btn://开始时间
  datechoosewheelviewdialog startdatechoosedialog = new datechoosewheelviewdialog(mainactivity.this, new datechoosewheelviewdialog.datechooseinterface() {
   @override
   public void getdatetime(string time, boolean longtimechecked) {
   mshowcontenttextview.settext(time);
   }
  });
  startdatechoosedialog.setdatedialogtitle("开始时间");
  startdatechoosedialog.showdatechoosedialog();
  break;
  case r.id.end_date_btn://结束时间
  datechoosewheelviewdialog enddatechoosedialog = new datechoosewheelviewdialog(mainactivity.this,
   new datechoosewheelviewdialog.datechooseinterface() {
    @override
    public void getdatetime(string time, boolean longtimechecked) {
    mshowcontenttextview.settext(time);
    }
   });
  enddatechoosedialog.settimepickergone(true);
  enddatechoosedialog.setdatedialogtitle("结束时间");
  enddatechoosedialog.showdatechoosedialog();
  break;
  case r.id.date_valid_btn://身份证有效期
  datechoosewheelviewdialog datevalidchoosedialog = new datechoosewheelviewdialog(mainactivity.this,
   new datechoosewheelviewdialog.datechooseinterface() {
    @override
    public void getdatetime(string time, boolean longtimechecked) {
    if (longtimechecked) {
     mshowcontenttextview.settext("长期 ");
    } else {
     mshowcontenttextview.settext(time);
    }
    }
   });
  datevalidchoosedialog.settimepickergone(true);
  datevalidchoosedialog.showlongterm(true);
  datevalidchoosedialog.setdatedialogtitle("身份证到期时间");
  datevalidchoosedialog.showdatechoosedialog();
  break;
  default:
  break;
 }

 }
}
</span></span>

代码下载地址:
github:https://github.com/hongxialiu/datechoosewheelviewdemo 
源码下载: wheelview滚轮时间选择控件

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。