【问题标题】:Android: use a datepicker and timepicker from within a DialogAndroid:在对话框中使用日期选择器和时间选择器
【发布时间】:2010-02-27 19:35:06
【问题描述】:

我遇到了一个我不知道如何解决的问题。

我有一个活动,当我单击链接到此活动的菜单的特定项目时,会显示一个对话框并用于添加一个项目。这个项目有一个日期和时间,但我在这个对话框中没有DatePickerTimePicker。我也尝试将活动传递给对话框并使用它来显示DatePicker,,但这不起作用。 在此之前,我在另一个 Activity 中处理了此类项目的创建。在这种情况下,它工作正常。但我发现 Dialog 更性感...... :-) 你有什么想法吗? 希望我不会太困惑...... 非常感谢,

我编辑这篇文章以分享我遇到困难的代码。

我有一个基本的Dialog 类尝试使用DatePickerTimePicker. 基本上,Eclipse 抱怨:

  • showDialog 未为 View.OnClickListener() 定义
  • onCreateDialog 方法:EventCreateDialog 类型的方法 onCreateDialog(int) 必须重写或实现超类型方法
  • DatePickerDialog 未定义(因为这不是活动)

所有这些东西都在一个 Activity 中工作,但我不能让它在一个对话框中工作。

非常感谢,

包 com.android.myapp;

public class TestDialog extends Dialog implements android.view.View.OnClickListener {
    static final int DATE_DIALOG_ID = 0;
    static final int TIME_DIALOG_ID = 1;
    private TextView mDateDisplay;
    private Button mPickDate;
    private Button mPickTime;
    private int mYear;
    private int mMonth;
    private int mDay;
    private int mHour;
    private int mMinute;
    private Button mButton_ok;
    private Button mButton_ko;

    private ReadyListener readyListener;

    private Context context;
    // the callback received when the user "sets" the date in the dialog
    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();
                }
            };
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
            new TimePickerDialog.OnTimeSetListener() {
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    mHour = hourOfDay;
                    mMinute = minute;
                    updateDisplay();
                }
            };

    public TestDialog(Context context, ReadyListener readyListener) {
        super(context);
        this.context = context;
        this.readyListener = readyListener;
    }

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

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

        mButton_ok = (Button) findViewById(R.id.button_ok);
        mButton_ko = (Button) findViewById(R.id.button_ko);

        // Add listeners
        mButton_ok.setOnClickListener(this);
        mButton_ko.setOnClickListener(this);

        mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
        mPickDate = (Button) findViewById(R.id.pickDate);
        mPickTime = (Button) findViewById(R.id.pickTime);
        // add a click listener to the button
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });
        mPickTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_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);
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
        updateDisplay();
    }

    @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;
    }

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

    @Override
    public void onClick(View v) {
        if (v == mButton_ok) {
            // Do stuff....
        }
        if (v == mButton_ko) {
            dismiss();
        }
    }

    public interface ReadyListener {
        public void ready(MyObj myObj);
    }
}

【问题讨论】:

  • 也许您可以分享似乎不起作用的代码?我之前在对话框中使用过 DatePicker 和 TimePicker 没有问题。
  • 非常感谢,很抱歉(我没有看到我得到回复)。我将分享代码,但只有一个问题,当您从对话框中调用 DatePicker 和 TimePicker 时,您会为它们提供哪种上下文?非常感谢,卢克
  • 您能否分享一下这是如何解决的。我有同样的问题。我们如何在自定义对话框中单击按钮时显示 TimePicker(或其他一些对话框)?即来自另一个对话框中的对话框?
  • 嗨,它没有得到解决,我以不同的方式处理这个问题(在视图中而不是在对话框中......)
  • 嗯...我现在也有这个单独的活动,一切正常。但是,当我尝试将其移至对话框(扩展对话框)时,不再能够使其正常工作。 :(

标签: android dialog datepicker


【解决方案1】:

这是我所拥有的:

public class EditRecordDialog extends Dialog {
  protected Context _context;
  private   Record  _record;

  public EditRecordDialog( Context context,
                           Record  record ) {
    super( context );
    _context = context;
    _record  = record
    Button buttonDate;
    buttonDate.setText( _record.getRecordDate() ); // returns 'mm-dd-yy'

  } // EditRecordDialog


// showDatePickerDialog ++++++++++++++++++++++++++++++++++++++++++++++++++++++
private void showDatePickerDialog( View view ) {
  String dateString;
  int    year, month, day;

  dateString = buttonDate.getText().toString();
  month = Integer.valueOf( dateString.substring( 0, 2 ) ) - 1; // month is zero based
  day   = Integer.valueOf( dateString.substring( 3, 5 ) );
  year  = Integer.valueOf( "20" + dateString.substring( 6, 8 ) );

  DatePickerDialog dpd = new DatePickerDialog( _context, dateSetListener, year, month, day );
  dpd.show();

} // showDatePickerDialog ----------------------------------------------------


// OnDateSetListener +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
  @Override public void onDateSet( DatePicker view, int year, int month, int day ) {
    buttonDate.setText( ConfigObjectDAO.formatDate( (month+1) + "-" + day + "-" + year ) );
  } // onDateSet
}; // OnDateSetListener ------------------------------------------------------
}

【讨论】:

    【解决方案2】:

    PickerViewSample.java

    package com.sai.samples.views;
    
    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.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.DatePicker;
    import android.widget.TextView;
    import android.widget.TimePicker;
    
    public class PickerViewSample extends Activity {
    
        static final int DATE_DIALOG_ID = 1;
        static final int TIME_DIALOG_ID = 2;
        private TextView dateDisplay;
        private Button pickDate;
        private int year, month, day;
        private TextView timeDisplay;
        private Button pickTime;
        private int hours, min;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            dateDisplay = (TextView)findViewById(R.id.TextView01);
            pickDate = (Button)findViewById(R.id.Button01);
    
            pickDate.setOnClickListener( new OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    showDialog(DATE_DIALOG_ID);
                }
    
            });
    
            final Calendar cal = Calendar.getInstance();
            year = cal.get(Calendar.YEAR);
            month = cal.get(Calendar.MONTH);
            day = cal.get(Calendar.DAY_OF_MONTH);
    
            updateDate();
    
            timeDisplay = (TextView)findViewById(R.id.TextView02);
            pickTime = (Button)findViewById(R.id.Button02);
    
            pickTime.setOnClickListener( new OnClickListener () {
    
                @Override
                public void onClick(View v) {
                    showDialog(TIME_DIALOG_ID);
    
                }
    
            });
    
            hours = cal.get(Calendar.HOUR);
            min = cal.get(Calendar.MINUTE);
    
            updateTime();
        }
    
        private void updateTime() {
            timeDisplay.setText(new StringBuilder().append(hours).append(':')
                    .append(min));
    
        }
    
        private void updateDate() {
            dateDisplay.setText(new StringBuilder().append(day).append('-')
                    .append(month + 1).append('-').append(year));
    
        }
    
        private DatePickerDialog.OnDateSetListener dateListener = 
            new DatePickerDialog.OnDateSetListener() {
    
                @Override
                public void onDateSet(DatePicker view, int yr, int monthOfYear,
                        int dayOfMonth) {
                    year = yr;
                    month = monthOfYear;
                    day = dayOfMonth;
                    updateDate();
                }
        };
    
        private TimePickerDialog.OnTimeSetListener timeListener = 
            new TimePickerDialog.OnTimeSetListener() {
    
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    hours = hourOfDay;
                    min = minute;
                    updateTime();
                }
    
        };
        protected Dialog onCreateDialog(int id){
            switch(id) {
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this, dateListener, year, month, day);
            case TIME_DIALOG_ID:
                return new TimePickerDialog(this, timeListener, hours, min, false);
            }
            return null;
    
        }
    }
    

    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:text="@string/date_text" 
        android:id="@+id/TextView01" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:textSize="26px" 
        android:typeface="sans"></TextView>
    <Button android:text="@string/date_button" 
        android:id="@+id/Button01" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"></Button>
    
    <TextView android:text="@string/time_text" 
        android:id="@+id/TextView02" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:textSize="26px" 
        android:typeface="sans"></TextView>
    <Button android:text="@string/time_button" 
        android:id="@+id/Button02" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"></Button>
    </LinearLayout>
    

    datepickerlayout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content">
    <DatePicker 
        android:id="@+id/DatePicker01" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"></DatePicker>
    </LinearLayout>
    

    【讨论】:

    • 您的答案是针对 Activity。他特别提到了“对话”。 :(
    【解决方案3】:

    将全局变量声明为:

    private int year, month, day, Hour, Minute;
    
    public static final int DATE_PICKER_ID = 1111;
    

    在 onCreate() 中

    // Get current date by calender
    final Calendar c = Calendar.getInstance();
    
    year = c.get(Calendar.YEAR);
    
    month = c.get(Calendar.MONTH);
    
    day = c.get(Calendar.DAY_OF_MONTH);
    

    点击按钮调用日期选择器

    showDialog(Constant.DATE_PICKER_ID);
    

    方法:

      @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case Constant.DATE_PICKER_ID:
    
                // open datepicker dialog.
                // set date picker for current date
                // add pickerListener listner to date picker
                return new DatePickerDialog(this, pickerListener, year, month, day);
    
            case Constant.TIME_PICKER_ID:
                return new TimePickerDialog(this, timeSetListener, Hour, Minute, false);
        }
        return null;
    }
    
    private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
    
        // when dialog box is closed, below method will be called.
        @Override
        public void onDateSet(DatePicker view, int selectedYear,
                              int selectedMonth, int selectedDay) {
    
            year = selectedYear;
            month = selectedMonth;
            day = selectedDay;
    
    
    
    
    
    
    
                text_date.setText(new StringBuilder().append(month + 1)
                        .append("/").append(day).append("/").append(year)
                        .append(" "));
    
    
        }
    };
    

    【讨论】:

      【解决方案4】:

      这应该可行:

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

      onCreateDialog 只能在活动中调用

      【讨论】:

        【解决方案5】:

        我在自己的 App 中使用此代码在对话框中创建 DatePicker:

        final Dialog dialog1 = new Dialog(YourActivity.this);
        dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog1.setContentView(R.layout.dialog_datepicker);
        DatePicker datePicker = dialog1.findViewById(R.id.datePicker);
        String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        datePicker.init(Integer.valueOf(date.substring(0, 4)), Integer.valueOf(date.substring(5, 7)) - 1, Integer.valueOf(date.substring(8, 10)), new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker datePicker, int i, int i1, int i2) {
                //do you stuff here 
            }
        });
        dialog1.show();
        

        【讨论】:

          猜你喜欢
          • 2011-08-23
          • 2021-08-11
          • 1970-01-01
          • 2016-11-30
          • 2014-03-23
          • 1970-01-01
          • 2011-08-14
          • 2023-03-07
          相关资源
          最近更新 更多