时间选择器
2019-04-15 本文已影响0人
君袅
1.以popupWindow的形式显示出来所以会引用一个xml文件
直接定义一个方法
Calendar calendar = Calendar.getInstance();
public int mDay;
public int mMonth;
public int mYear;
public void setDate(final TextView pEnd) {
//点击"日期"按钮布局 设置日期
//通过自定义控件AlertDialog实现
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View view = (LinearLayout) getLayoutInflater().inflate(R.layout.date_dialog, null);
final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
//设置日期简略显示 否则详细显示 包括:星期\周
datePicker.setCalendarViewShown(false);
//初始化当前日期
calendar.setTimeInMillis(System.currentTimeMillis());
datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH), null);
//设置date布局
builder.setView(view);
builder.setTitle("设置日期信息");
builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//日期格式
StringBuffer sb = new StringBuffer();
sb.append(String.format("%d-%02d-%02d",
datePicker.getYear(),
datePicker.getMonth() + 1,
datePicker.getDayOfMonth()));
pEnd.setText(sb);
//赋值后面闹钟使用
mYear = datePicker.getYear();
mMonth = datePicker.getMonth();
mDay = datePicker.getDayOfMonth();
dialog.cancel();
}
});
builder.setNegativeButton("取 消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.create().show();
}
引用的是date_dialog的xml里写中:
<DatePicker
android:datePickerMode="spinner"
android:calendarViewShown="false"
android:id="@+id/date_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_gravity="center" >
</DatePicker>