Android 中的日期选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3299392/
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 09:35:17  来源:igfitidea点击:

Date picker in Android

androiddatepicker

提问by Sanjeev

Can any one post sample code for a simple date picker in Android.

任何人都可以发布 Android 中简单日期选择器的示例代码。

If date picker is not possible in Android, an option to choose a date is needed.

如果 Android 中无法使用日期选择器,则需要选择日期的选项。

回答by Sebastian

Use the DatePicker

使用日期选择器

http://developer.android.com/reference/android/widget/DatePicker.html

http://developer.android.com/reference/android/widget/DatePicker.html

It is availible since API Level 1

自 API 级别 1 起可用

Here a example how to use the DatePickerDialog.

这是一个如何使用 DatePickerDialog 的示例。

First add a TextView and a Button to your layout.xml

首先在 layout.xml 中添加一个 TextView 和一个 Button

<Button android:id="@+id/myDatePickerButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Choose Date"/>

<TextView android:id="@+id/showMyDate"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"/>

Next you have to initialize the Button and TextView in the onCreate Method of your layout. You need this class variables

接下来,您必须在布局的 onCreate 方法中初始化 Button 和 TextView。你需要这个类变量

private int mYear;
private int mMonth;
private int mDay;

private TextView mDateDisplay;
private Button mPickDate;

static final int DATE_DIALOG_ID = 0;

Here the onCreate method

这里的 onCreate 方法

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

    mDateDisplay = (TextView) findViewById(R.id.showMyDate);        
    mPickDate = (Button) findViewById(R.id.myDatePickerButton);

    mPickDate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showDialog(DATE_DIALOG_ID);
        }
    });

    // get the current date
    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

    // display the current date
    updateDisplay();
}

UpdateDisplay method:

更新显示方法:

private void updateDisplay() {
    this.mDateDisplay.setText(
        new StringBuilder()
                // Month is 0 based so add 1
                .append(mMonth + 1).append("-")
                .append(mDay).append("-")
                .append(mYear).append(" "));
}

The callback listener for the DatePickDialog

DatePickDialog 的回调侦听器

private DatePickerDialog.OnDateSetListener mDateSetListener =
    new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, 
                              int monthOfYear, int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            updateDisplay();
        }
    };

The onCreateDialog method, called by showDialog()

由 showDialog() 调用的 onCreateDialog 方法

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

Hope it helps, used it and it works fine.

希望它有帮助,使用它并且它工作正常。

Example from

示例来自

http://developer.android.com/guide/tutorials/views/hello-datepicker.html

http://developer.android.com/guide/tutorials/views/hello-datepicker.html

回答by Ankit jain

public class dateresult extends Activity
{
private TextView tvdisplaydate;
private DatePicker dpResult;
private Button bntchangedate;

private int year;
private int month;
private int day;
static final int DATE_DIALOG_ID = 999;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.result);
    setCurrentdateonView();
    addListenerOnButton();

     }
              public void setCurrentdateonView(){

                  tvdisplaydate = (TextView)findViewById(R.id.tvdate);
                  dpResult = (DatePicker) findViewById(R.id.dpResult);

                  final Calendar c = Calendar.getInstance();
                  year = c.get(Calendar.YEAR);
                  month = c.get(Calendar.MONTH) ;
                  day = c.get(Calendar.DAY_OF_MONTH);

                  tvdisplaydate.setText(new StringBuffer()                   .append(month+1).append("-").append(day).append("-").append(year).append(""));
                  dpResult.init(year, month, day, null);                                  
              }             
             public void addListenerOnButton(){                  
                 bntchangedate = (Button)findViewById(R.id.bntchangedate);
                 bntchangedate.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                    showDialog(DATE_DIALOG_ID);

                    }
                });              
             }                
             @Override
            protected Dialog onCreateDialog(int id) {
                // TODO Auto-generated method stub
                 switch(id){

                 case DATE_DIALOG_ID:
                     return new DatePickerDialog(this,datePickerLisner,year,month,day);

                 }
                return null;
            }                
             private DatePickerDialog.OnDateSetListener datePickerLisner = new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int Selectyear,int Selectmonth, int Selectday) {
                    year= Selectyear;
                    month= Selectmonth;
                    day = Selectday;
                    tvdisplaydate.setText(new StringBuilder() 
                    .append(Selectmonth+1).append("-").append(Selectday).append("-").append(Selectyear).append(""));
                            dpResult.init(year, month, day, null);                  
                }
            };
}


<?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:orientation="vertical" >

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

<TextView
    android:id="@+id/lbldate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Current Date (M-D-YYYY) :" 
    android:textAppearance="?android:attr/textAppearanceLarge"/>

<TextView
    android:id="@+id/tvdate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    android:textAppearance="?android:attr/textAppearanceLarge" />
<DatePicker
    android:id="@+id/dpResult"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>

回答by bradj

Here is an updated version which documents backwards compatibility with the Support Library:

这是一个更新的版本,它记录了与支持库的向后兼容性:

http://developer.android.com/guide/topics/ui/controls/pickers.html#DatePicker

http://developer.android.com/guide/topics/ui/controls/pickers.html#DatePicker

回答by Mayank Saini

public class DatePickerDialogFragment extends DialogFragment{
    //ResidenceActivity date = new ResidenceActivity();
    Handler mHandler ;
    int mDay;
    int mMonth;
    int mYear;

    public DatePickerDialogFragment(Handler h){
        /** Getting the reference to the message handler instantiated in MainActivity class */
        mHandler = h;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState){

        /** Creating a bundle object to pass currently set date to the fragment */
        Bundle b = getArguments();

        /** Getting the day of month from bundle */
        mDay = b.getInt("set_day");

        /** Getting the month of year from bundle */
        mMonth = b.getInt("set_month");

        /** Getting the year from bundle */
        mYear = b.getInt("set_year");

        /** DatePickerDialog's "Set" click listener */
        DatePickerDialog.OnDateSetListener listener  = new DatePickerDialog.OnDateSetListener() {
         //   @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                mDay = dayOfMonth;
                mMonth = monthOfYear;
                mYear = year;

                /** Creating a bundle object to pass currently set date to the fragment */
                Bundle b = new Bundle();

                /** Adding currently set day to bundle object */
                b.putInt("set_day", mDay);

                /** Adding currently set month to bundle object */
                b.putInt("set_month", mMonth);

                /** Adding currently set year to bundle object */
                b.putInt("set_year", mYear);

                /** Adding Current date in a string to bundle object */
                b.putString("set_date", Integer.toString(mDay) + "/" + Integer.toString(mMonth+1) + "/" + Integer.toString(mYear));

                /** Creating an instance of Message */
                Message m = new Message();

                /** Setting bundle object on the message object m */
                m.setData(b);



                /** Message m is sending using the message handler instantiated in MainActivity class */
                mHandler.sendMessage(m);




            }
        };

        /** Opening the DatePickerDialog window */
        return new DatePickerDialog(getActivity(), listener, mYear, mMonth, mDay);
    }
}

回答by async8192

The accepted answer doesn't handle the user clicking cancel in the date picker. In that case, nothing should be updated.

接受的答案不处理用户在日期选择器中单击取消。在这种情况下,不应更新任何内容。

I wanted the same thing as OP, but I just wanted it in-line. Here's what I used:

我想要与 OP 相同的东西,但我只是想要它在线。这是我使用的:

Create the callback that will be called when the date picker OK button is clicked:

创建将在单击日期选择器 OK 按钮时调用的回调:

public void datePicked(int year, int month, int day) {
    buttonDate.setText(String.valueOf(year) + "/" + 
          String.valueOf(month) + "/" + String.valueOf(day));
}

Then use the following code in the method where you create a button to pick the date:

然后在创建按钮的方法中使用以下代码来选择日期:

    buttonDate = (Button) rootView.findViewById(R.id.button_select_date);
    buttonDate.setText("Select Date");
    buttonDate.setOnClickListener(new View.OnClickListener() {
        public void setReturnDate(int year, int month, int day) {
            datePicked(year, month, day);
        }

        @Override
        public void onClick(View v) {
            Dialog datePickerDialog = new DatePickerDialog(activity, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                }
            }, leagueEndDate.get(Calendar.YEAR), leagueEndDate.get(Calendar.MONTH), leagueEndDate
                    .get(Calendar.DAY_OF_MONTH));
            datePickerDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    setReturnDate(((DatePickerDialog) dialog).getDatePicker().getYear(),
                            ((DatePickerDialog) dialog).getDatePicker().getMonth(), ((DatePickerDialog) dialog)
                                    .getDatePicker().getDayOfMonth());
                }
            });
            datePickerDialog.show();
        }
    });

回答by Vinod Joshi

Step 1 : create a java file:

package com.example.babs;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import  android.app.FragmentManager;


public class EditUserInfo extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_edit_view);

    }

    public class DatePickerFragment extends DialogFragment
    implements DatePickerDialog.OnDateSetListener {


        // pgrm mark ---- ---- ----- ---- ---- ----- ---- ---- -----  ---- ---- -----

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            // Do something with the date chosen by the user
        }

    }


    public void showDatePickerDialog(View v) {

        FragmentManager fragmentManager = getFragmentManager();

        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(fragmentManager, "datePicker");
    }

}// end main class EditUserInfo

step 2: your xml file must contain : 

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:fillViewport="true" >
</ScrollView>
<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:text="@string/pick_date" 
    android:onClick="showDatePickerDialog" />

回答by user roy

use: import java.util.Calendar;

使用:导入java.util.Calendar;

instead: import android.icu.util.Calendar.

相反:导入 android.icu.util.Calendar。

this package supports only for API level-24 not less than that. This is the package we need to use to get Calendar on the dialog box,

该软件包仅支持不低于 24 级的 API。这是我们需要用来在对话框中获取日历的包,

this works fine.

这工作正常。

回答by Shiv Buyya

To use DatePicker add below source code in your OnCreate of Activity.

要使用 DatePicker,请在您的 OnCreate 活动中添加以下源代码。

PS: make sure that android:focusable="false"should be provided for your EditText.

PS:确保应为您的 EditText 提供android:focusable="false"

// Edittext in your layout file
date = (EditText) findViewById(R.id.date);
// onclick on edit text
date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    final Calendar c = Calendar.getInstance();
    int mYear = c.get(Calendar.YEAR); // current year
    int mMonth = c.get(Calendar.MONTH); // current month
    int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
    // date picker dialog
    datePickerDialog = new DatePickerDialog(MainActivity.this,
         new DatePickerDialog.OnDateSetListener() {

                 @Override
                 public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                     // set day of month , month and year value in the edit text
                     date.setText(dayOfMonth + "/"+ (monthOfYear + 1) + "/" + year);
                 }
         }, mYear, mMonth, mDay);
                datePickerDialog.show();
    }
});

When you click on the Edittext it will open the Calendar.

当您单击 Edittext 时,它将打开日历。