大家在项目开发中经常会遇到选择时间问题,DatePicker是日期选择器,TimePicker是时间选择器,此博客实现的是当点击展示时间的EditText时弹出对话框选择开始日期和结束日期,并将开始日期和结束日期展示在EditText上。布局界面如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:gravity="center_horizontal"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/start_time"
android:textSize="18sp"
/>
<DatePicker
android:id="@+id/start_datepicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:calendarViewShown="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/end_time"
android:textSize="18sp"
/>
<DatePicker
android:id="@+id/end_datepicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:calendarViewShown="false" />
</LinearLayout>
自定义的工具类如下:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import com.xly.tourgb.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.LinearLayout;
public class DateTimePickDialogUtils implements OnDateChangedListener{
private DatePicker startDatePicker;
private DatePicker endDatePicker;
private AlertDialog ad;
private String dateTime;
private String initStartDate;
private String initEndDate;
private Activity activity;
/**
* 日期弹出选择框构造函数
* @param activity :调用的父activity
* @param initStartDate 初始开始日期值
* @param initEndDate 初始结束日期值
*/
public DateTimePickDialogUtils(Activity activity, String initStartDate, String initEndDate) {
this.activity = activity;
this.initStartDate = initStartDate;
this.initEndDate = initEndDate;
}
public void init(DatePicker startDatePicker, DatePicker endDatePicker) {
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
if (!(null == initStartDate || "".equals(initStartDate)) && !(null == initEndDate || "".equals(initEndDate))) {
calendar1 = this.getCalendarByInintData(initStartDate);
calendar2 = this.getCalendarByInintData(initEndDate);
} else {
initStartDate = calendar1.get(Calendar.YEAR) + "年"
+ calendar1.get(Calendar.MONTH) + "月"
+ calendar1.get(Calendar.DAY_OF_MONTH) + "日 ";
initEndDate = calendar2.get(Calendar.YEAR) + "年"
+ calendar2.get(Calendar.MONTH) + "月"
+ calendar2.get(Calendar.DAY_OF_MONTH) + "日 ";
}
//如果是TimePicker就是用setCurrentHour和setCurrentMinute方法
startDatePicker.init(calendar1.get(Calendar.YEAR),
calendar1.get(Calendar.MONTH),
calendar1.get(Calendar.DAY_OF_MONTH), this);
endDatePicker.init(calendar2.get(Calendar.YEAR),
calendar2.get(Calendar.MONTH),
calendar2.get(Calendar.DAY_OF_MONTH), this);
}
/**
* 弹出日期选择框方法
*
* @param inputDate
* :为需要设置的日期时间文本编辑框
* @return
*/
public AlertDialog dateTimePicKDialog(final EditText inputDate) {
LinearLayout dateTimeLayout = (LinearLayout) activity
.getLayoutInflater().inflate(R.layout.datetime_dialog, null);
startDatePicker = (DatePicker) dateTimeLayout.findViewById(R.id.start_datepicker);
endDatePicker = (DatePicker) dateTimeLayout.findViewById(R.id.end_datepicker);
init(startDatePicker, endDatePicker);
//如果是时间选择器,需要设置setIs24HourView属性
ad = new AlertDialog.Builder(activity)
.setTitle("开始结束日期选择")
.setView(dateTimeLayout)
.setPositiveButton("设置", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
inputDate.setText(dateTime);
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
inputDate.setText("");
}
}).show();
onDateChanged(null, 0, 0, 0);
return ad;
}
public void onDateChanged(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// 获得日历实例
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.set(startDatePicker.getYear(), startDatePicker.getMonth(),
startDatePicker.getDayOfMonth());
calendar2.set(endDatePicker.getYear(), endDatePicker.getMonth(),
endDatePicker.getDayOfMonth());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
dateTime = sdf.format(calendar1.getTime()) + "-" + sdf.format(calendar2.getTime());
ad.setTitle(dateTime);
}
/**
* 实现将初始日期2017年04月11日 拆分成年 月 日 ,并赋值给calendar
* @param initDateTime 初始日期值 字符串型
* @return Calendar
*/
private Calendar getCalendarByInintData(String initDateTime) {
Calendar calendar = Calendar.getInstance();
// 将初始日期2017年04月11日 拆分成年 月 日
//1.获取年月日
String date = spliteString(initDateTime, "日", "index", "front"); // 日期
//2.根据获取的年月日拆分成年和月日
String yearStr = spliteString(date, "年", "index", "front"); // 年份
String monthAndDay = spliteString(date, "年", "index", "back"); // 月日
//3.根据获取的月日再次拆分成月和日
String monthStr = spliteString(monthAndDay, "月", "index", "front"); // 月
String dayStr = spliteString(monthAndDay, "月", "index", "back"); // 日
//int currentYear = Integer.parseInt(yearStr.trim());
int currentYear = Integer.valueOf(yearStr.trim()).intValue();
//注意月份获取出来要-1
int currentMonth = Integer.valueOf(monthStr.trim()).intValue() - 1;
int currentDay = Integer.valueOf(dayStr.trim()).intValue();
//把当前的年月日赋值给calendar对象
calendar.set(currentYear, currentMonth, currentDay);
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;
}
}
Activity如下:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import com.xly.base.utils.DateTimePickDialogUtils;
import com.xly.tourgb.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
public class DateTimePickerActivity extends Activity{
private EditText dateTime;
private SimpleDateFormat sdf;
private String date;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.date_time_picker);
dateTime = (EditText) findViewById(R.id.date_time);
Calendar calendar = Calendar.getInstance();
//日期格式必须跟工具类中的一样
sdf = new SimpleDateFormat("yyyy年MM月dd日");
date = sdf.format(new Date());
//EditText默认显示当前时间
dateTime.setText(date);
//EditText重新设置时间
dateTime.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
DateTimePickDialogUtils dateTimePicKDialog =
new DateTimePickDialogUtils(DateTimePickerActivity.this, date, date);
dateTimePicKDialog.dateTimePicKDialog(dateTime);
}
});
}
}
效果图如下:
对于时间选择器,本人找到几篇好的文章,大家可以根据自己项目需要参考,文章如下:
http://www.open-open.com/lib/view/open1389605122336.html
http://www.cnblogs.com/mcxiaobing/p/5907327.html
http://www.admin5.com/article/20170321/728254.shtml
http://www.cnblogs.com/jilianggqq/p/4139510.html