android应用程序中的日期时间选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2055509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:23:10  来源:igfitidea点击:

DateTime picker in android application

androidandroid-widget

提问by Luc

Is there any android widget that enable to pick the date and the time at the same time ? I already use the basic time pickerand date picker.

有没有可以同时选择日期和时间的android小部件?我已经使用了基本的时间选择器日期选择器

But they are not that sexy and user friendly (I found). Do you know if a widget including both date and time exists? Thanks a lot, Luc

但它们不是那么性感和用户友好(我发现)。您知道是否存在同时包含日期和时间的小部件吗?非常感谢,卢克

采纳答案by CommonsWare

There is nothing built into Android that offers this.

Android 中没有任何内置功能可以提供此功能。

EDIT: Andriod now offers built-in pickers. Check @Oded answer

编辑:Andriod 现在提供内置选择器。检查@Oded 答案

回答by Oded Breiner

Put both DatePickerand TimePickerin a layout XML.

DatePicker和 都TimePicker放在布局 XML 中。

date_time_picker.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>

The code:

编码:

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();

回答by Abhishek

Use this function it will enable you to pic date and time one by one then set it to global variable date. No library no XML.

使用此功能,您可以将日期和时间一一拍摄,然后将其设置为全局变量日期。没有图书馆没有 XML。

Calendar date;
public void showDateTimePicker() {
   final Calendar currentDate = Calendar.getInstance();
   date = Calendar.getInstance();
   new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
       @Override
       public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            date.set(year, monthOfYear, dayOfMonth);
            new TimePickerDialog(context, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    date.set(Calendar.HOUR_OF_DAY, hourOfDay);
                    date.set(Calendar.MINUTE, minute);
                    Log.v(TAG, "The choosen one " + date.getTime());
                }
            }, currentDate.get(Calendar.HOUR_OF_DAY), currentDate.get(Calendar.MINUTE), false).show();
       }
   }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
}

回答by JDJ

combined DatePicker and TimePicker in DialogFragment for Android

Android DialogFragment 中结合 DatePicker 和 TimePicker

I created a libraryto do this. It also has customizable colors!

我创建了一个来做到这一点。它还具有可定制的颜色!

It's very simple to use.

使用起来非常简单。

First you create a listener:

首先创建一个监听器:

private SlideDateTimeListener listener = new SlideDateTimeListener() {

    @Override
    public void onDateTimeSet(Date date)
    {
        // Do something with the date. This Date object contains
        // the date and time that the user has selected.
    }

    @Override
    public void onDateTimeCancel()
    {
        // Overriding onDateTimeCancel() is optional.
    }
};

Then you create and show the dialog:

然后创建并显示对话框:

new SlideDateTimePicker.Builder(getSupportFragmentManager())
    .setListener(listener)
    .setInitialDate(new Date())
    .build()
    .show();

I hope you find it useful.

希望对你有帮助。

回答by Jaydeep Khamar

Call the time picker dialog in the DatePickerupdate time method. It'll not be called at the same time but when you press DatePickerset button. The time picker dialog will open. The method is given below.

DatePicker更新时间方法中调用时间选择器对话框。它不会同时被调用,而是在您按下DatePicker设置按钮时调用。时间选择器对话框将打开。方法如下。

package com.android.date;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

public class datepicker extends Activity {

    private TextView mDateDisplay;
    private Button mPickDate;
    private int mYear;
    private int mMonth;
    private int mDay;
    private TextView mTimeDisplay;
    private Button mPickTime;

    private int mhour;
    private int mminute;

    static final int TIME_DIALOG_ID = 1;

    static final int DATE_DIALOG_ID = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mDateDisplay =(TextView)findViewById(R.id.date);
        mPickDate =(Button)findViewById(R.id.datepicker);
        mTimeDisplay = (TextView) findViewById(R.id.time);
        mPickTime = (Button) findViewById(R.id.timepicker);

        //Pick time's click event listener
        mPickTime.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });

        //PickDate's click event listener 
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mhour = c.get(Calendar.HOUR_OF_DAY);
        mminute = c.get(Calendar.MINUTE);
    }

    //-------------------------------------------update date---//    
    private void updateDate() {
        mDateDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mDay).append("/")
                    .append(mMonth + 1).append("/")
                    .append(mYear).append(" "));
        showDialog(TIME_DIALOG_ID);
    }

      //-------------------------------------------update time---//    
    public void updatetime() {
        mTimeDisplay.setText(
                new StringBuilder()
                        .append(pad(mhour)).append(":")
                        .append(pad(mminute))); 
    }

    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);


    //Datepicker dialog generation  

    private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, 
                                  int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateDate();
            }
        };


     // Timepicker dialog generation
        private TimePickerDialog.OnTimeSetListener mTimeSetListener =
            new TimePickerDialog.OnTimeSetListener() {
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    mhour = hourOfDay;
                    mminute = minute;
                    updatetime();
                }
            };

        @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this,
                            mDateSetListener,
                            mYear, mMonth, mDay);

            case TIME_DIALOG_ID:
                return new TimePickerDialog(this,
                        mTimeSetListener, mhour, mminute, false);

            }
            return null;
        }
}

the main.xml is given below

下面给出了 main.xml

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

    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="@string/hello"/>

    <TextView android:id="@+id/time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""/>

    <Button
        android:id="@+id/timepicker"
        android:text="Change Time" 
        android:layout_height="wrap_content" 
        android:layout_width="wrap_content"/>

    <TextView 
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""/>

    <Button android:id="@+id/datepicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="200dp"
        android:text="Change the date"/>

</LinearLayout>

回答by J-Jamet

I also wanted to combine a DatePicker and a TimePicker. So I create an API to handle both in one interface! :)

我还想结合一个 DatePicker 和一个 TimePicker。所以我创建了一个 API 来在一个界面中处理两者!:)

https://github.com/Kunzisoft/Android-SwitchDateTimePicker

https://github.com/Kunzisoft/Android-SwitchDateTimePicker

enter image description here

在此处输入图片说明

You can also use SublimePicker

您也可以使用SublimePicker

回答by Mark B

The URLs you link to show how to pop up a dialog with a time picker and another dialog with a date picker. However you need to be aware that you can use those UI widgets directly in your own layout. You could build your own dialog that includes both a TimePicker and DatePicker in the same view, thus accomplishing what I think you are looking for.

您链接的 URL 显示如何弹出一个带有时间选择器的对话框和另一个带有日期选择器的对话框。但是您需要注意,您可以直接在您自己的布局中使用这些 UI 小部件。您可以构建自己的对话框,在同一视图中同时包含 TimePicker 和 DatePicker,从而实现我认为您正在寻找的内容。

In other words, instead of using TimePickerDialog and DatePickerDialog, just use the UI widgets TimePickerand DatePickerdirectly in your own dialog or activity.

换句话说,不要使用 TimePickerDialog 和 DatePickerDialog,而是直接在您自己的对话框或活动中使用 UI 小部件TimePickerDatePicker

回答by ptashek

I was facing the same problem in one of my projects and have decided to make a custom widget that has both the date and the time picker in one user-friendly dialog. You can get the source code along with an example at http://code.google.com/p/datetimepicker/. The code is licensed under Apache 2.0.

我在我的一个项目中遇到了同样的问题,并决定制作一个自定义小部件,它在一个用户友好的对话框中同时具有日期和时间选择器。您可以在http://code.google.com/p/datetimepicker/ 上获取源代码和示例。该代码在 Apache 2.0 下获得许可。

回答by Cristian

I forked, updated, refactored and mavenized the android-dateslider project. It is on Github now:

我对 android-dateslider 项目进行了分叉、更新、重构和 mavenized。它现在在 Github 上:

https://github.com/casidiablo/date-slider

https://github.com/casidiablo/date-slider