如果你对Android自定义Dialog对话框的几种方法还不太了解,可以点击这里传送你过去进行了解
Android 原生的日期时间选择控件有时候在项目中使用给人的感觉会比较难看,带来的体验差。
先来上组图片对比下原生和自定义样式后的效果图:
下面两张图原生的效果:
这是自定义样式后的效果(当然我这里的自定义样式比较随便,只要有好的设计,相信你可以做出更好看的样式,掌握自定义控件的方法很重要,哈哈):
废话不说了,开始上关键代码:
自定义日期选择对话框 DataPicker.class :
import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.TextView;
import com.wj.R;
import java.util.Calendar;
import java.util.Date;
/**
* Created by EASY on 2018/5/23.
*/
public class DataPicker extends Dialog implements View.OnClickListener{
private DatePicker datePicker;
private OnDateClick clicker;
private TextView cancelButton,okButton;
private Context context;
private int year;
private int monthOfYear;
private int dayOfMonth;
public DataPicker(@NonNull Context context, OnDateClick callBack, int year, int monthOfYear, int dayOfMonth) {
super(context);
this.clicker = callBack;
this.context = context;
this.year = year;
this.monthOfYear = monthOfYear;
this.dayOfMonth = dayOfMonth;
init();
}
private void init() {
// //用来取消标题栏 在setcontentview之前调用 否则会报错 android.util.AndroidRuntimeException:requestFeature() must be called before adding content
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
Window window = this.getWindow();
window.setContentView(R.layout.view_date_picker_dialog);
View view = this.getWindow().getDecorView();
WindowManager.LayoutParams lp = window.getAttributes();
DisplayMetrics d = context.getResources().getDisplayMetrics(); // 获取屏幕宽、高用
lp.width = (int) (d.widthPixels * 0.75); // 宽度设置为屏幕的0.75
lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
window.setAttributes(lp);
datePicker = (DatePicker) view.findViewById(R.id.datePicker);
datePicker.init(year, monthOfYear, dayOfMonth, new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {}
});
cancelButton = (TextView) view.findViewById(R.id.cancelButton);
okButton = (TextView) view.findViewById(R.id.okButton);
Calendar mCalendar = Calendar.getInstance();
mCalendar.setTime(new Date());
cancelButton.setOnClickListener(this);
okButton.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.cancelButton:
dismiss();
break;
case R.id.okButton:
onOkButtonClick();
dismiss();
break;
}
}
/**
* 确认 按钮 点击 事件
*/
private void onOkButtonClick() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, datePicker.getYear());
int month =datePicker.getMonth();
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
calendar.getTime();
if (clicker != null) {
clicker.onDataSelect(calendar.getTime());
}
}
public DatePicker getDatePicker(){
return datePicker;
}
public interface OnDateClick {
void onDataSelect(Date date);
}
}
自定义日期对话框的布局文件:view_date_picker_dialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Your Birthday"
android:textColor="#000"
android:layout_gravity="left"
android:textSize="16sp" />
<RelativeLayout
android:id="@+id/contentLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:orientation="vertical"
>
<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:calendarViewShown="false"
android:datePickerMode="spinner" />
<LinearLayout
android:id="@+id/buttonGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@+id/datePicker"
android:orientation="horizontal">
<TextView
android:id="@+id/cancelButton"
android:layout_width="60dp"
android:layout_height="30dp"
android:gravity="center"
android:text="CANCEL"
android:textColor="@color/colorPrimary"
android:textSize="14sp" />
<TextView
android:id="@+id/okButton"
android:layout_width="60dp"
android:layout_height="30dp"
android:layout_marginLeft="30dp"
android:background="@color/colorPrimary"
android:gravity="center"
android:text="OK"
android:textColor="#FFF"
android:textSize="14sp" />
LinearLayout>
RelativeLayout>
LinearLayout>
自定义时间对话框TimePicker.class
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import com.wj.R;
/**
* Created by EASY on 2018/5/23.
*/
public class TimePicker extends Dialog implements View.OnClickListener{
private android.widget.TimePicker timePicker;
private OnTimeClick clicker;
private TextView cancelButton,okButton;
private Context context;
private int hourOfDay;
private int minute;
private boolean is24HourView;
public TimePicker(@NonNull Context context, OnTimeClick callBack, int hourOfDay, int minute, boolean is24HourView) {
super(context);
this.clicker = callBack;
this.context = context;
this.hourOfDay = hourOfDay;
this.minute = minute;
this.is24HourView = is24HourView;
init();
}
private void init() {
// //用来取消标题栏 在setcontentview之前调用 否则会报错 android.util.AndroidRuntimeException:requestFeature() must be called before adding content
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
Window window = this.getWindow();
window.setContentView(R.layout.view_time_picker_dialog);
View view = this.getWindow().getDecorView();
WindowManager.LayoutParams lp = window.getAttributes();
DisplayMetrics d = context.getResources().getDisplayMetrics(); // 获取屏幕宽、高用
lp.width = (int) (d.widthPixels * 0.75); // 宽度设置为屏幕的0.75
lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
window.setAttributes(lp);
timePicker = (android.widget.TimePicker) view.findViewById(R.id.timePicker);
timePicker.setCurrentHour(hourOfDay);
timePicker.setCurrentMinute(minute);
timePicker.setIs24HourView(is24HourView);
cancelButton = (TextView) view.findViewById(R.id.btn_cancel);
okButton = (TextView) view.findViewById(R.id.btn_ok);
cancelButton.setOnClickListener(this);
okButton.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_cancel:
dismiss();
break;
case R.id.btn_ok:
onOkButtonClick();
dismiss();
break;
}
}
/**
* 确认 按钮 点击 事件
*/
@SuppressLint("NewApi")
private void onOkButtonClick() {
if (clicker != null) {
clicker.onTimeSelect(timePicker.getCurrentHour(),timePicker.getCurrentMinute());
}
}
public android.widget.TimePicker getDatePicker(){
return timePicker;
}
public interface OnTimeClick {
void onTimeSelect(int hour,int minute);
}
}
自定义时间对话框布局文件:view_time_picker_dialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Your Time of Birth"
android:textColor="#000"
android:layout_gravity="left"
android:textSize="16sp" />
<RelativeLayout
android:id="@+id/contentLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:orientation="vertical"
>
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:calendarViewShown="false"
android:timePickerMode="spinner" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@+id/timePicker"
android:orientation="horizontal">
<TextView
android:id="@+id/btn_cancel"
android:layout_width="60dp"
android:layout_height="30dp"
android:gravity="center"
android:text="CANCEL"
android:textColor="@color/colorPrimary"
android:textSize="14sp" />
<TextView
android:id="@+id/btn_ok"
android:layout_width="60dp"
android:layout_height="30dp"
android:layout_marginLeft="30dp"
android:background="@color/colorPrimary"
android:gravity="center"
android:text="OK"
android:textColor="#FFF"
android:textSize="14sp" />
LinearLayout>
RelativeLayout>
LinearLayout>
然后开始调用:
注意,下面两个方法是对这两个自定义控件的调用封装,你只需要在你要点击用来选择日期和时间的按钮的监听事件中调用就行(然后特别提醒:喜欢直接Ctrl+c和Ctrl+v的同学一定注意,这里贴的是kotlin 的代码,复制到java代码里面报错别怪我哦,哈哈,最好别直接复制粘贴,理解学习最重要!!!)
private fun selectData() {
var dialog: DataPicker = DataPicker(context!!, DataPicker.OnDateClick { date ->
var y = Integer.parseInt(SimpleDateFormat("yyyy").format(date))
var m = Integer.parseInt(SimpleDateFormat("MM").format(date))
var d = Integer.parseInt(SimpleDateFormat("dd").format(date))
mYear = y.toString()
mMonth = m.toString()
mDay = d.toString()
fragment_me_data_tv?.text = mYear + "-" + mMonth + "-" + mDay
fragment_login_img.visibility = View.GONE
upDateTiem()
},mOldYear!!, mOldMonth!!-1 , mOldDay!!)
dialog.getDatePicker().setCalendarViewShown(false)
dialog.show()
}
private fun selectTime() {
var timePicker: TimePicker = TimePicker(context!!, TimePicker.OnTimeClick {hourOfDay, minute ->
mHour = if (hourOfDay.toString().length != 1) hourOfDay.toString() else "0" + hourOfDay.toString()
mMin = if (minute.toString().length != 1) minute.toString() else "0" + minute.toString()
fragment_me_time_tv?.text = mHour + ":" + mMin
fragment_login_img.visibility = View.GONE
upDateTiem()
}, mOldHour!!, mOldMin!!, true)
timePicker.show()
}
好了,到此一个美观大方,简洁实用的日期时间选择对话框就做好了,还可以根据自己的喜欢随便修改样式,比用系统的体验强多了。
最后记录一点小知识,关于系统时间选择器的。
系统的时间选择器TimePicker控件,在不同的手机和版本号上,样式会出现不统一的情况,有时是滑动选择的方式,有时会出现时钟的样式,原因是在Android6.0中,TimePicker控件的默认样式为转盘的样式,就像这个样子:
如果想要显示为之前的滚动样式的话也很简单,只要在布局文件中设置TimePicker的timePickerMode属性为spinner就好了。
这样设置后显示的样式就是滚动的样式了
我也是之前对这个不是太清晰,所以偶然的机会发现了这个api,所以也在这里做下笔记,方便自己以后温习,回顾,其实说白了,就是我记性不是太好,记下来防止自己忘记后到处再找,哈哈!分享到此结束,有更好方案或者喜欢交流技术的同学可以互相关注了解,或者一起评论探讨,谢谢!