Android:DatePicker 和 DatePicker 对话框

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

Android: DatePicker and DatePicker Dialog

androidandroid-datepicker

提问by lemoncodes

I have this code here on the options menu

我在选项菜单上有这个代码

Dialog dialog = new Dialog(ScheduleActivity.this);
dialog.setTitle("Add Event");
dialog.setContentView(R.layout.add_even_on);
Button datePicker = (Button) dialog.findViewById(R.id.datePicker);
final DialogFragment dateFrag = new MyDatePicker();
    datePicker.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                dateFrag.show(getSupportFragmentManager(), "datePicker");               
            }
        });
dialog.show();

when, say "Add Event" on the option menu is clicked, a Dialog appears, with a button that shows a DatePickerDialogand beside it is a TextViewthat reflects the date chosen in the DatePickerDialog, here is the class I got from Androids Developer on how to use the DatePickerDialog.

当单击选项菜单上的“添加事件”时,会出现一个对话框,其中有一个按钮显示DatePickerDialog,旁边是一个TextView,它反映了在DatePickerDialog 中选择的日期,这是我从 Androids Developer 获得的类如何使用 DatePickerDialog。

class MyDatePicker extends DialogFragment implements DatePickerDialog.OnDateSetListener {
 int pYear;
 int pDay;
 int pMonth;

@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) {
    pYear = year;
    pDay = day;
    pMonth = month;
  }
}

So my problem is that how do i get the Value in milleseconds when i click "Set" on the DatePickerDialog which in turn automatically closes it, and returns to my Dialog which contains the button which open the DatePickerDialog and a Textview which reflects watever date is chosen the DatePickerDialog... i wont show the one i chose inside the DatePickerDialog...

所以我的问题是,当我在 DatePickerDialog 上单击“设置”时,如何以毫秒为单位获取值,然后它会自动关闭它,并返回到我的对话框,其中包含打开 DatePickerDialog 的按钮和反映水日期的 Textview 是选择了 DatePickerDialog ......我不会显示我在 DatePickerDialog 中选择的那个......

Here is a picture of what i mean,

这是我的意思的图片,

So when i click on the Pick Date Button a DatePickerDialog box appears as seen on the next picture enter image description here

因此,当我单击“选择日期”按钮时,会出现一个 DatePickerDialog 框,如下图所示 在此处输入图片说明

enter image description here

在此处输入图片说明

and when i click set, i wanted to take into account the value in millseconds from that DatePickerDialog

当我单击设置时,我想考虑该 DatePickerDialog 中以毫秒为单位的值

回答by Hpsaturn

Old dialogs are deprecated. Implements fragments:

旧对话框已弃用。实现片段:

Migrate your Activity to Fragment Activity:

将您的活动迁移到片段活动:

public class YourActivity extends FragmentActivity 

Create Fragment Dialog:

创建片段对话框:

public class TimePickerFragment extends DialogFragment {

    private OnDateSetListener listener;

    public TimePickerFragment(OnDateSetListener listener) {
        this.listener=listener;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for 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 TimePickerDialog and return it
        return new DatePickerDialog(getActivity(), listener, year,month,day);
    }

}

Implements interface (package: import android.app.DatePickerDialog.OnDateSetListener):

实现接口(包:import android.app.DatePickerDialog.OnDateSetListener):

public class YourActivity extends FragmentActivity implements OnDateSetListener{

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {

    }

}

Add showDialog function:

添加 showDialog 函数:

public class YourActivity extends FragmentActivity implements OnDateSetListener{

    showDateDialog(){

        FragmentManager fm = getSupportFragmentManager();
        TimePickerFragment newFragment = new TimePickerFragment(this);
        newFragment.show(fm, "date_picker");

    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {

    }

}

回答by januprasad

Here I Provide Some Code Hope It Helps You..

在这里我提供一些代码希望它可以帮助你..

public class NewReminder extends Activity {
private static final int DATE_DIALOG_ID = 1;
private int year;
private int month;
private int day;
EditText editTextDate;
private String currentDate;
private Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.addnewreminder);
    initialize();
    context = getApplicationContext();
    OnClickListener listenerDate = new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            final Calendar c = Calendar.getInstance();
            year = c.get(Calendar.YEAR);
            month = c.get(Calendar.MONTH);
            day = c.get(Calendar.DAY_OF_MONTH);
            showDialog(DATE_DIALOG_ID);
        }
    };
    editTextDate.setOnClickListener(listenerDate);

}

private void initialize() {
    // TODO Auto-generated method stub

    editTextDate = (EditText) findViewById(R.id.editTextDate);

}


private void updateDisplay() {
    currentDate = new StringBuilder().append(day).append(".")
            .append(month + 1).append(".").append(year).toString();

    Log.i("DATE", currentDate);
}

OnDateSetListener myDateSetListener = new OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker datePicker, int i, int j, int k) {

        year = i;
        month = j;
        day = k;
        updateDisplay();
        editTextDate.setText(currentDate);
    }
};



@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
        return new DatePickerDialog(this, myDateSetListener, year, month,
                day);
    }
    return null;
}
}

回答by MaxEcho

In XML add a TextView and a Button

在 XML 中添加一个 TextView 和一个按钮

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

<Button
    android:id="@+id/search"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Search" />

Add following code in java file

在java文件中添加以下代码

public class DatePickerDialogExample extends Activity {

    TextView txtDate;
    private int mYear, mMonth, mDay, mHour, mMinute;

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


        txtDate = (TextView) findViewById(R.id.searchText);
        Button search = (Button) findViewById(R.id.search);
        search.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Process to get Current Date
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);

            // Launch Date Picker Dialog
            DatePickerDialog dpd = new DatePickerDialog(PrayTimeActivity.this,
                    new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year,
                                int monthOfYear, int dayOfMonth) {
                            // Display Selected date in textbox
                            txtDate.setText(dayOfMonth + "-"
                                    + (monthOfYear + 1) + "-" + year);

                        }
                    }, mYear, mMonth, mDay);
                dpd.show();
            }
        });


    }

}

回答by Bhavinkumar Patel

Try this code it is definately work:

试试这个代码,它肯定是有效的:

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

            DatePickerDialog dpd = new DatePickerDialog(getActivity(),
                    new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year,
                                int monthOfYear, int dayOfMonth) {

                            birth_Date.setText(dayOfMonth + "-"
                                    + (monthOfYear + 1) + "-" + year);
                        }
                    }, mYear, mMonth, mDay);
            dpd.show();

回答by Abhishek Patil

You can try this code.. it will surely helpful to u.. No Doubt!

你可以试试这个代码..它肯定会对你有帮助..毫无疑问!

    protected Dialog onCreateDialog(int id) {

    Calendar c=Calendar.getInstance();
    int Sysday=c.get(Calendar.DAY_OF_MONTH);
    int Sysmonth=c.get(Calendar.MONTH);
    int Sysyear=c.get(Calendar.YEAR);

    int Sysmin=c.get(Calendar.MINUTE);
    int Syshour=c.get(Calendar.HOUR);


    switch (id) {
    case TIME_DIALOG:

        return new TimePickerDialog(this, myTimePicker , Syshour, Sysmin, false);

    case DATE_DIALOG:
        return new DatePickerDialog(this, myDatePicker, Sysyear, Sysmonth, Sysday);
    }
    return null;
}

回答by Faraz Ahmed

This is my helper function which get context and TextView as parameter and sets Date on that text view when user select a date:

这是我的辅助函数,它获取上下文和 TextView 作为参数,并在用户选择日期时在该文本视图上设置日期:

        public static void showDate(final Context context, final TextView textView) {

    if (textView != null) {
        final Calendar myCalendar = Calendar.getInstance();
        DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // TODO Auto-generated method stub
                myCalendar.set(Calendar.YEAR, year);
                myCalendar.set(Calendar.MONTH, monthOfYear);
                myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                String myFormat = "MM/dd/yy"; // In which you need put here
                SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
                //UIHelper.showLongToastInCenter(context, sdf.format(myCalendar.getTime()));
                textView.setText(sdf.format(myCalendar.getTime()));
            }

        };
        new DatePickerDialog(context, date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show();
    } else {
        UIHelper.showLongToastInCenter(context, "Unable to show Date picker");
    }
}

回答by Aklesh Singh

Use it like this in Koltin

在 Koltin 中像这样使用它

DatePickerDialog(this as Activity, DatePickerDialog.OnDateSetListener { p0, y, m, _ -> func.invoke(y, m + 1) }, c.get(Calendar.YEAR),
        c.get(Calendar.MONTH),
        c.get(Calendar.DAY_OF_MONTH))
        .show()

Use it from anywhere

从任何地方使用它

tvDateFrom.click {
        showDatePicker(c) { y, m ->
            Utils.debugger("DATE FROM ", " y + $y m $m")
            tvDateFrom.text = "$m-$y".toDate()
        }
    }

回答by Karan Datwani

Calendar c1 = Calendar.getInstance();    
int year = c1.get(Calendar.YEAR);
int month = c1.get(Calendar.MONTH);
int day = c1.get(Calendar.DAY_OF_MONTH);
DatePickerDialog.OnDateSetListener myDateListener  = new DatePickerDialog.OnDateSetListener() {

       public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
                   if(arg0.isShown()){

                                     //do further code here

                              }
                            }

                          };
        DatePickerDialog dp = new DatePickerDialog(YourActivity.this, myDateListener, year, month, day);
        dp.show();