android实现双日期选择控件(可隐藏日,只显示年月)

android实现双日期选择控件(可隐藏日,只显示年月),第1张

概述在安卓开发中,会碰到选开始日期和结束日期的问题。特别是在使用Pad时,如果d出一个Dialog,能够同时选择开始日期和结束日期,那将是极好的。我在开发中在DatePickerDialog的基础上做了修改,实现了这种Dialog。效果

在安卓开发中,会碰到选开始日期和结束日期的问题。特别是在使用Pad时,如果d出一个Dialog,能够同时选择开始日期和结束日期,那将是极好的。我在开发中在DatePickerDialog的基础上做了修改,实现了这种Dialog。效果如下:

具体实现方法为:

先新建一个安卓项目DoubleDatePicker,在res/layout文件夹下新建date_picker_dialog.xml,内容如下:

<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"  androID:layout_wIDth="wrap_content"  androID:layout_height="wrap_content"  androID:gravity="center_horizontal"  androID:orIEntation="horizontal"  androID:paddingtop="10dp" >  <linearLayout    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    androID:gravity="center_horizontal"    androID:orIEntation="vertical"    androID:padding="5dip" >    <TextVIEw      androID:layout_wIDth="wrap_content"      androID:layout_height="wrap_content"      androID:text="开始日期" />    <DatePicker      androID:ID="@+ID/datePickerStart"      androID:layout_wIDth="wrap_content"      androID:layout_height="wrap_content"      androID:calendarVIEwShown="false" />  </linearLayout>  <ImageVIEw    androID:layout_wIDth="wrap_content"    androID:layout_height="fill_parent"    androID:src="@drawable/fenge" />  <linearLayout    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    androID:gravity="center_horizontal"    androID:orIEntation="vertical"    androID:padding="5dip" >    <TextVIEw      androID:layout_wIDth="wrap_content"      androID:layout_height="wrap_content"      androID:text="结束日期" />    <DatePicker      androID:ID="@+ID/datePickerEnd"      androID:layout_wIDth="wrap_content"      androID:layout_height="wrap_content"      androID:calendarVIEwShown="false" />  </linearLayout></linearLayout>

然后,在src的 默认包下新建文件DoubleDatePickerDialog.java,内容如下:

/* * copyright (C) 2007 The AndroID Open Source Project * * licensed under the Apache license,Version 2.0 (the "license"); * you may not use this file except in compliance with the license. * You may obtain a copy of the license at * * * Unless required by applicable law or agreed to in writing,software * distributed under the license is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implIEd. * See the license for the specific language governing permissions and * limitations under the license. */package com.example.doubledatepicker;import java.lang.reflect.FIEld;import androID.app.AlertDialog;import androID.content.Context;import androID.content.DialogInterface;import androID.content.DialogInterface.OnClickListener;import androID.os.Bundle;import androID.vIEw.LayoutInflater;import androID.vIEw.VIEw;import androID.Widget.DatePicker;import androID.Widget.DatePicker.OnDateChangedListener;/** * A simple dialog containing an {@link androID.Widget.DatePicker}. * * <p> * See the <a href="{@docRoot}guIDe/topics/ui/controls/pickers.HTML">Pickers</a> * guIDe. * </p> */public class DoubleDatePickerDialog extends AlertDialog implements OnClickListener,OnDateChangedListener {  private static final String START_YEAR = "start_year";  private static final String END_YEAR = "end_year";  private static final String START_MONTH = "start_month";  private static final String END_MONTH = "end_month";  private static final String START_DAY = "start_day";  private static final String END_DAY = "end_day";  private final DatePicker mDatePicker_start;  private final DatePicker mDatePicker_end;  private final OnDateSetListener mCallBack;  /**   * The callback used to indicate the user is done filling in the date.   */  public interface OnDateSetListener {    /**     * @param vIEw     *      The vIEw associated with this Listener.     * @param year     *      The year that was set.     * @param monthOfYear     *      The month that was set (0-11) for compatibility with     *      {@link java.util.Calendar}.     * @param dayOfMonth     *      The day of the month that was set.     */    voID onDateSet(DatePicker startDatePicker,int startYear,int startMonthOfYear,int startDayOfMonth,DatePicker endDatePicker,int endYear,int endMonthOfYear,int endDayOfMonth);  }  /**   * @param context   *      The context the dialog is to run in.   * @param callBack   *      How the parent is notifIEd that the date is set.   * @param year   *      The initial year of the dialog.   * @param monthOfYear   *      The initial month of the dialog.   * @param dayOfMonth   *      The initial day of the dialog.   */  public DoubleDatePickerDialog(Context context,OnDateSetListener callBack,int year,int monthOfYear,int dayOfMonth) {    this(context,callBack,year,monthOfYear,dayOfMonth);  }  public DoubleDatePickerDialog(Context context,int theme,dayOfMonth,true);  }  /**   * @param context   *      The context the dialog is to run in.   * @param theme   *      the theme to apply to this dialog   * @param callBack   *      How the parent is notifIEd that the date is set.   * @param year   *      The initial year of the dialog.   * @param monthOfYear   *      The initial month of the dialog.   * @param dayOfMonth   *      The initial day of the dialog.   */  public DoubleDatePickerDialog(Context context,int dayOfMonth,boolean isDayVisible) {    super(context,theme);    mCallBack = callBack;    Context themeContext = getContext();    setbutton(button_POSITIVE,"确 定",this);    setbutton(button_NEGATIVE,"取 消",this);    // setbutton(button_POSITIVE,// themeContext.getText(androID.R.string.date_time_done),this);    setIcon(0);    LayoutInflater inflater = (LayoutInflater) themeContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);    VIEw vIEw = inflater.inflate(R.layout.date_picker_dialog,null);    setVIEw(vIEw);    mDatePicker_start = (DatePicker) vIEw.findVIEwByID(R.ID.datePickerStart);    mDatePicker_end = (DatePicker) vIEw.findVIEwByID(R.ID.datePickerEnd);    mDatePicker_start.init(year,this);    mDatePicker_end.init(year,this);    // update@R_502_5979@(year,dayOfMonth);    // 如果要隐藏当前日期,则使用下面方法。    if (!isDayVisible) {      hIDDay(mDatePicker_start);      hIDDay(mDatePicker_end);    }  }  /**   * 隐藏DatePicker中的日期显示   *    * @param mDatePicker   */  private voID hIDDay(DatePicker mDatePicker) {    FIEld[] datePickerfFIElds = mDatePicker.getClass().getDeclaredFIElds();    for (FIEld datePickerFIEld : datePickerfFIElds) {      if ("mDaySpinner".equals(datePickerFIEld.getname())) {        datePickerFIEld.setAccessible(true);        Object dayPicker = new Object();        try {          dayPicker = datePickerFIEld.get(mDatePicker);        } catch (illegalaccessexception e) {          e.printstacktrace();        } catch (IllegalArgumentException e) {          e.printstacktrace();        }        // datePicker.getCalendarVIEw().setVisibility(VIEw.GONE);        ((VIEw) dayPicker).setVisibility(VIEw.GONE);      }    }  }  public voID onClick(DialogInterface dialog,int which) {    // Log.d(this.getClass().getSimplename(),String.format("which:%d",// which));    // 如果是“取 消”按钮,则返回,如果是“确 定”按钮,则往下执行    if (which == button_POSITIVE)      tryNotifyDateSet();  }  @OverrIDe  public voID onDateChanged(DatePicker vIEw,int month,int day) {    if (vIEw.getID() == R.ID.datePickerStart)      mDatePicker_start.init(year,month,day,this);    if (vIEw.getID() == R.ID.datePickerEnd)      mDatePicker_end.init(year,day);  }  /**   * 获得开始日期的DatePicker   *   * @return The calendar vIEw.   */  public DatePicker getDatePickerStart() {    return mDatePicker_start;  }  /**   * 获得结束日期的DatePicker   *   * @return The calendar vIEw.   */  public DatePicker getDatePickerEnd() {    return mDatePicker_end;  }  /**   * Sets the start date.   *   * @param year   *      The date year.   * @param monthOfYear   *      The date month.   * @param dayOfMonth   *      The date day of month.   */  public voID updateStartDate(int year,int dayOfMonth) {    mDatePicker_start.updateDate(year,dayOfMonth);  }  /**   * Sets the end date.   *   * @param year   *      The date year.   * @param monthOfYear   *      The date month.   * @param dayOfMonth   *      The date day of month.   */  public voID updateEndDate(int year,int dayOfMonth) {    mDatePicker_end.updateDate(year,dayOfMonth);  }  private voID tryNotifyDateSet() {    if (mCallBack != null) {      mDatePicker_start.clearFocus();      mDatePicker_end.clearFocus();      mCallBack.onDateSet(mDatePicker_start,mDatePicker_start.getYear(),mDatePicker_start.getMonth(),mDatePicker_start.getDayOfMonth(),mDatePicker_end,mDatePicker_end.getYear(),mDatePicker_end.getMonth(),mDatePicker_end.getDayOfMonth());    }  }  @OverrIDe  protected voID onStop() {    // tryNotifyDateSet();    super.onStop();  }  @OverrIDe  public Bundle onSaveInstanceState() {    Bundle state = super.onSaveInstanceState();    state.putInt(START_YEAR,mDatePicker_start.getYear());    state.putInt(START_MONTH,mDatePicker_start.getMonth());    state.putInt(START_DAY,mDatePicker_start.getDayOfMonth());    state.putInt(END_YEAR,mDatePicker_end.getYear());    state.putInt(END_MONTH,mDatePicker_end.getMonth());    state.putInt(END_DAY,mDatePicker_end.getDayOfMonth());    return state;  }  @OverrIDe  public voID onRestoreInstanceState(Bundle savedInstanceState) {    super.onRestoreInstanceState(savedInstanceState);    int start_year = savedInstanceState.getInt(START_YEAR);    int start_month = savedInstanceState.getInt(START_MONTH);    int start_day = savedInstanceState.getInt(START_DAY);    mDatePicker_start.init(start_year,start_month,start_day,this);    int end_year = savedInstanceState.getInt(END_YEAR);    int end_month = savedInstanceState.getInt(END_MONTH);    int end_day = savedInstanceState.getInt(END_DAY);    mDatePicker_end.init(end_year,end_month,end_day,this);  }}

这些代码是以DatePickerDialog.java为基础修改的。总的来说,阅读源码是一种好习惯。这里面最需要注意的是hIDDay方法,该方法如果调用,则隐藏“日”的选择框,只能选择“年月”。这个方法的实现也比较有难度,需要通过反射,找出DatePicker中表示日的字段,并将其设置为隐藏。

还有一点需要注意的是,为了让控件显示更加好看,我用了一张名字为fenge.png的图片,图片在我提供的源码中可以找到。

下面就需要编辑activity_main.xml了,这个内容相当简单,只要一个显示的text和一个button即可,代码如下:

<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"  androID:ID="@+ID/linearLayout01"  androID:layout_wIDth="fill_parent"  androID:layout_height="fill_parent"  androID:orIEntation="vertical" >  <EditText    androID:ID="@+ID/et"    androID:layout_wIDth="fill_parent"    androID:layout_height="wrap_content"    androID:cursorVisible="false"    androID:editable="false" />  <button    androID:ID="@+ID/dateBtn"    androID:layout_wIDth="fill_parent"    androID:layout_height="wrap_content"    androID:text="日期对话框" /></linearLayout>

最后,在MainActivity.java中,加入测试代码:

package com.example.doubledatepicker;import java.util.Calendar;import androID.app.Activity;import androID.os.Bundle;import androID.vIEw.VIEw;import androID.Widget.button;import androID.Widget.DatePicker;import androID.Widget.TextVIEw;public class MainActivity extends Activity {  button btn;  TextVIEw et;  @OverrIDe  protected voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVIEw(R.layout.activity_main);    btn = (button) findVIEwByID(R.ID.dateBtn);    et = (TextVIEw) findVIEwByID(R.ID.et);    btn.setonClickListener(new VIEw.OnClickListener() {      Calendar c = Calendar.getInstance();      @OverrIDe      public voID onClick(VIEw v) {        // 最后一个false表示不显示日期,如果要显示日期,最后参数可以是true或者不用输入        new DoubleDatePickerDialog(MainActivity.this,new DoubleDatePickerDialog.OnDateSetListener() {          @OverrIDe          public voID onDateSet(DatePicker startDatePicker,int endDayOfMonth) {            String textString = String.format("开始时间:%d-%d-%d\n结束时间:%d-%d-%d\n",startYear,startMonthOfYear + 1,startDayOfMonth,endYear,endMonthOfYear + 1,endDayOfMonth);            et.setText(textString);          }        },c.get(Calendar.YEAR),c.get(Calendar.MONTH),c.get(Calendar.DATE),true).show();      }    });  }}

可以看到,在新建DoubleDatePickerDialog时, 我们实现了一个new DoubleDatePickerDialog.OnDateSetListener()的匿名类,这个类被DoubleDatePickerDialog引用,当DoubleDatePickerDialog中的“确 定”按钮被点击时,就会调用匿名类的onDateSet方法。(这也是事件绑定的基本原理)。

DoubleDatePickerDialog构造函数的最后一个参数,true为显示日期,false为不显示日期。

当最后一个参数为true时,显示效果如下:

当最后一个参数为false时,显示如下

 

源码下载地址:http://xiazai.jb51.net/201701/yuanma/DoubleDatePicker_jb51.rar

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

总结

以上是内存溢出为你收集整理的android实现双日期选择控件(可隐藏日,只显示年月)全部内容,希望文章能够帮你解决android实现双日期选择控件(可隐藏日,只显示年月)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1147100.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存