Android原生控件中时间日期是分开的,但是有时我们的实际工作中可能是需要两个联动选择的,这时就需要我们自己将两个控件组合起来封装了一个工具类.
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uzqKcZX5-1588584849734)(http://www.myllcn.com/dassets/album/200422/1.gif#pic_center)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZrdpNHSQ-1588584754272)(http://www.myllcn.com/dassets/album/200422/2.gif)]
一. 创建工具类
关于控件主题以原生为主,大家可以修改themeId进行对应修改,上图就分别是主题2和主题4.绑定控件直接将TextView类型修改为对应控件对象就行.
package com.myllcn.specialdeal;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;
/**
* @author keiferju
* @time 2020/4/21 8:50 AM
* @title 时间日期选择器
* @desc
*
*/
public class DateTimePicker implements DatePickerDialog.OnDateSetListener,TimePickerDialog.OnTimeSetListener{
private static Context context;
private static DatePickerDialog datePickerDialog;
private static TimePickerDialog pickerDialog;
private static Calendar calendar;
private static TextView editText; // 绑定控件
private String dt = "";
Integer themeId = 2; // 主题ID
@SuppressLint("ResourceType")
@RequiresApi(api = Build.VERSION_CODES.N)
public void init(Context context1, TextView editText1)
{
calendar=Calendar.getInstance();
editText=editText1;
context=context1;
datePickerDialog=new DatePickerDialog(context,themeId,this, calendar.get(Calendar.YEAR), calendar
.get(Calendar.MONTH), calendar
.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
dt = String.valueOf(new StringBuilder()
.append(year)
.append("-")
.append((month + 1) < 10 ? "0"
+ (month + 1) : (month + 1))
.append("-")
.append((day < 10) ? "0" + day : day));
// editText.setText( );
initTimePicker(context);
}
public void initTimePicker(Context context1){
context=context1;
pickerDialog=new TimePickerDialog(context,themeId,this,8,00,true);
pickerDialog.show();
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String s=(hourOfDay<10?"0"+hourOfDay:hourOfDay)+":"+(minute<10?"0"+minute:minute)+ ":"+ "00";
dt = dt +" "+s;
editText.setText(dt);
}
}
二. 使用:
// 1.创建工具类对象
final DateTimePicker dateTimePicker = new DateTimePicker();
//2.引用对象的init方法
dateTimePicker.init(context, textView);
三. 如果还需要获取事件日期选择完的事件,那么可以采用addTextChangedListener监听.
textView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
不足之处,欢迎访问DLLCN的学习笔记进行批评与讨论,一起成长,一起学习.