android - 如何在 Android 中创建日期和时间选择器?

标签 android android-widget

是否有任何 android 小部件可以同时选择日期和时间? 我已经使用基本的 time pickerdate picker .

但它们并不那么性感和用户友好(我发现)。你知道是否存在包含日期和时间的小部件吗?

非常感谢, 卢克

最佳答案

DatePickerTimePicker 都放入布局 XML。

date_time_picker.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:padding="8dp"
    android:layout_height="match_parent">

    <DatePicker
        android:id="@+id/date_picker"
        android:layout_width="match_parent"
        android:calendarViewShown="true"
        android:spinnersShown="false"
        android:layout_weight="4"
        android:layout_height="0dp" />

    <TimePicker
        android:id="@+id/time_picker"
        android:layout_weight="4"
        android:layout_width="match_parent"
        android:layout_height="0dp" />

    <Button
        android:id="@+id/date_time_set"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:text="Set"
        android:layout_height="0dp" />

</LinearLayout>

代码:

final View dialogView = View.inflate(activity, R.layout.date_time_picker, null);
final AlertDialog alertDialog = new AlertDialog.Builder(activity).create();

dialogView.findViewById(R.id.date_time_set).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

         DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.date_picker);
         TimePicker timePicker = (TimePicker) dialogView.findViewById(R.id.time_picker);

         Calendar calendar = new GregorianCalendar(datePicker.getYear(),
                            datePicker.getMonth(),
                            datePicker.getDayOfMonth(),
                            timePicker.getCurrentHour(),
                            timePicker.getCurrentMinute());

         time = calendar.getTimeInMillis();
         alertDialog.dismiss();
    }});
alertDialog.setView(dialogView);
alertDialog.show();

关于android - 如何在 Android 中创建日期和时间选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2055509/

相关文章:

java - Android 应用程序,如何以编程方式在 TableLayout 单元格中居中对齐 ImageView

android - Volley,BasicNetwork.performRequest : Unexpected response code 405,,同时制作 StringRequest

android - 通过java为android中的RemoteView设置重力

java - 复选框导致小部件出错

安卓小部件 :how to determine which button was clicked?

Android:从线程访问ui元素

滚动时 Android ListView 样式问题与背景

Android 播放从 Base64 字符串慢速声音转换而来的 PCM 字节数组

android - 如何检查处理程序是否有回调

android - 如何获取水平 ScrollView 的宽度