一 . TimePicker 时间选择器
(1)布局dialog_timer_picker.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:orientation="vertical"> <TimePicker android:id="@+id/tpSetTimer" android:layout_width="wrap_content" android:layout_gravity="center" android:layout_height="wrap_content" android:layout_marginTop="5dip" /> </LinearLayout>
注:使用的是系统自带的TimePicker,自定义的可百度参考。
(2)调用
AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = getLayoutInflater().inflate(R.layout.dialog_timer_picker, null); final android.widget.TimePicker timePicker = (android.widget.TimePicker) view.findViewById(R.id.tpSetTimer); //初始化时间 final Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); timePicker.setIs24HourView(true); timePicker.setCurrentHour(openHour); //再次打开时显示的小时 timePicker.setCurrentMinute(openMinute); //再次打开时显示的分钟 //设置time布局 builder.setView(view); builder.setTitle("设置时间信息"); builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { openHour = timePicker.getCurrentHour(); //获取选定的小时 openMinute = timePicker.getCurrentMinute(); //获取选定的分钟 //时间小于10的数字 前面补0 如01:12:00 tvOpenTime.setText(new StringBuilder().append(openHour < 10 ? "0" + openHour : openHour).append(":") .append(openMinute < 10 ? "0" + openMinute : openMinute)); //显示选定的时间 } }); builder.setNegativeButton("取 消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.create().show();
这样一个简单的时间选择器就完成了。
The end !