您的位置:首页 > 其它

日期选择器 DatePicker 的使用方法

2016-05-04 15:33 811 查看
收集了别人的代码 自己再添加另外过滤日期范围的部分

1. 调用代码 (布局代码在下面)

/**
* 弹出日期选择框
* @param view
*/
public void btn1(View view) {
LayoutInflater l = LayoutInflater.from(this);
View v = l.inflate(R.layout.dialog, null);
final DatePicker datePicker = (DatePicker) v.findViewById(R.id.datepicker);

datePicker.init(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), new DatePicker.OnDateChangedListener() {

@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

if (isDateAfter(view)) {
view.init(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), this);
Toast.makeText(MainActivity.this, "超出范围-今天", Toast.LENGTH_SHORT).show();
}
if (isDateBefore(view)) {
view.init(2010, 0, 1, this);
Toast.makeText(MainActivity.this, "超出范围-最低范围", Toast.LENGTH_SHORT).show();
}
}

//超出当月
private boolean isDateAfter(DatePicker tempView) {
if (tempView.getYear() > c.get(Calendar.YEAR)) {
return true;
} else if (tempView.getYear() == c.get(Calendar.YEAR)) {
if (tempView.getMonth() > c.get(Calendar.MONTH)) {
return true;
} else if (tempView.getMonth() == c.get(Calendar.MONTH)) {
if (tempView.getDayOfMonth() > c.get(Calendar.DATE)) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}

//小于最低范围
private boolean isDateBefore(DatePicker tempView) {
if (tempView.getYear() < 2010) {
return true;
} else
return false;
}
});
Dialog dialog = new AlertDialog.Builder(this)
.setTitle( datePicker.getYear() + "年" + (datePicker.getMonth() + 1) + "月" + datePicker.getDayOfMonth() + "日")
.setView(v)
.setIcon(R.drawable.ic_launcher)
.setNeutralButton("设置", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {

Toast.makeText(MainActivity.this, datePicker.getYear() + "年" + (datePicker.getMonth() + 1)
+ "月" + datePicker.getDayOfMonth() + "日", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();

}
}).create();

dialog.show();
}


2.布局代码 dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<DatePicker
android:id="@+id/datepicker"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: