android AlertDialog返回日期值

时间:2014-08-13 00:44:19

标签: java android alertdialog

Mike Dalasay的例子在这里找到: http://www.codeofaninja.com/2011/07/android-alertdialog-example.html

他介绍了AlertDialog的例子。我想在这些示例中使用时间和日期对话框,使函数返回由时间和日期选择器设置的值。

作为Java和Android的新手,我知道如何将返回void更改为String,但我不知道如何将选择器值传递给返回值。

这是他的原始代码:

使用日期选择器显示AlertDialog。

public void alertDatePicker() {

    /*
     * Inflate the XML view. activity_main is in res/layout/date_picker.xml
     */
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.date_picker, null, false);

    // the time picker on the alert dialog, this is how to get the value
    final DatePicker myDatePicker = (DatePicker) view.findViewById(R.id.myDatePicker);

    // so that the calendar view won't appear
    myDatePicker.setCalendarViewShown(false);

    // the alert dialog
    new AlertDialog.Builder(MainActivity.this).setView(view)
            .setTitle("Set Date")
            .setPositiveButton("Go", new DialogInterface.OnClickListener() {
                @TargetApi(11)
                public void onClick(DialogInterface dialog, int id) {

                    /*
                     * In the docs of the calendar class, January = 0, so we
                     * have to add 1 for getting correct month.
                     * http://goo.gl/9ywsj
                     */
                    int month = myDatePicker.getMonth() + 1;
                    int day = myDatePicker.getDayOfMonth();
                    int year = myDatePicker.getYear();

                    showToast(month + "/" + day + "/" + year);

                    dialog.cancel();

                }

            }).show();
}

showToast在哪里我会设置String myDate并以某种方式从函数中获取返回值:

public String alertDatePicker() {

感谢。

1 个答案:

答案 0 :(得分:0)

目前,您在month课程中声明了变量day yearAlertDialog。如果你移动到调用方法或类,那么它们的范围将是不同的。

例如

 int month = 0;
 int day = 0;

 new AlertDialog.Builder .....

 }).show ();

 System.out.println (month);
相关问题