问题 - 使用两个日期时间选择器

时间:2012-01-04 05:30:24

标签: android datetime datetimepicker

我正在尝试使用两个日期和时间选择器(如fromdate和To date)获取所选日期。如果我从日期中选择,我可以将fromdate添加到textview。但是,如果我选择第二个datepicker(todate)更新相同的textview(Fromdate textview)。

      public class F2Activity extends InfosoftActivity 

      {
  private int mYear;
  private int mMonth;
  private int mDay;
  private int mYear2;
  private int mMonth2;
  private int mDay2;
  private TextView mDateDisplay;
  private TextView mDateDisplay2;
  private Button mPickDate;
  private Button mPickDate2;
  static final int DATE_DIALOG_ID = 0;
  static final int DATE_DIALOG_IDD = 0;
            public String AAA;
            public String BBB;



    public void onCreate(Bundle savedInstanceState) 
    {
    super.onCreate(savedInstanceState);
    setTheme(android.R.style.Theme_Black);

    setContentView(R.layout.activity_f2);

    Button BtnView=(Button) findViewById(R.id.BtnView);
    Button BtnDownload=(Button) findViewById(R.id.BtnDownload);

        mDateDisplay = (TextView) findViewById(R.id.showMyDate); 
        mDateDisplay2 = (TextView) findViewById(R.id.showMyDatee); 

        mPickDate = (Button) findViewById(R.id.myDatePickerButton);
        mPickDate2 = (Button) findViewById(R.id.myDatePickerButton2);



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



        mPickDate2.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_IDD);
            }
        });


        // get the current date
        final Calendar c2 = Calendar.getInstance();
        mYear2 = c2.get(Calendar.YEAR);
        mMonth2 = c2.get(Calendar.MONTH);
        mDay2 = c2.get(Calendar.DAY_OF_MONTH);

        // display the current date
        updateDisplayTo();

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

            }
         private void updateDisplayTo() 
         {
        this.mDateDisplay2.setText(
        new StringBuilder()
                // Month is 0 based so add 1
            .append(mMonth2 + 1).append("-")
            .append(mDay2).append("-")
            .append(mYear2).append(" "));

    }



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

            }
        };

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



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

                @Override
                public void onDateSet(DatePicker view, int year, int 
                                    monthOfYear,
                        int dayOfMonth) {
                    // TODO Auto-generated method stub

                      mYear2 = year;
                      mMonth2 = monthOfYear;
                      mDay2 = dayOfMonth;
                      updateDisplayTo();

                }
            };        



             protected Dialog onCreateDialog2 (int id)

                       {
                      switch (id)

                      {
                       case DATE_DIALOG_IDD:
                       return new DatePickerDialog(this,
                               mDateSetListener2,
                                  mYear2, mMonth2, mDay2);
                      }

                        return null;
                       }                        

                                           }

3 个答案:

答案 0 :(得分:1)

检查我亲自在我的代码中使用过...它对我有用..

public class StartEndActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */

    Button btnFromDate;
    Button btnToDate;
    Button btnFromTime;
    Button btnToTime;
    Button btnStartEndBack;
    Button btnStartEndDone;

    TextView txtFrom;
    TextView txtToDate;
    CheckBox chAlldays;

    private int mYear;
    private int mMonth;
    private int mDay;
    private int mHour;
    private int mMinute;

    private int mEYear;
    private int mEMonth;
    private int mEDay;
    private int mEHour;
    private int mEMinute;
    private int pStartHour, pEndHour;

    static final int DATE_DIALOG_ID = 0;
    static final int TIME_DIALOG_ID = 1;
    static final int END_DATE_DIALOG_ID = 2;
    static final int END_TIME_DIALOG_ID = 3;

    boolean IsAllDay = false;
    TimePickerDialog tc;
    TimePickerDialog Etc;
    String startDate;
    String startTime;
    String endDate;
    String endTime;

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

        btnToDate = (Button) findViewById(R.id.btnToDate);
        btnToTime = (Button) findViewById(R.id.btnToTime);
        btnFromDate = (Button) findViewById(R.id.btnFromDate);
        btnFromTime = (Button) findViewById(R.id.btnFromTime);
        btnStartEndBack = (Button) findViewById(R.id.btnStartEndBack);
        btnStartEndDone = (Button) findViewById(R.id.btnStartEndDone);

        txtToDate = (TextView) findViewById(R.id.txtTo);
        txtFrom = (TextView) findViewById(R.id.txtFrom);

        chAlldays = (CheckBox) findViewById(R.id.chAlldays);

        btnToDate.setOnClickListener(this);
        btnToTime.setOnClickListener(this);
        chAlldays.setOnClickListener(this);
        btnFromDate.setOnClickListener(this);
        btnFromTime.setOnClickListener(this);
        btnStartEndBack.setOnClickListener(this);
        btnStartEndDone.setOnClickListener(this);

        IsAllDay = Boolean.parseBoolean(getIntent().getSerializableExtra(
                "IsAllDay").toString());

        chAlldays.setChecked(IsAllDay);

        /*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);
        mMinute = c.get(Calendar.MINUTE);
        pStartHour = c.get(Calendar.HOUR_OF_DAY);


        mEYear = c.get(Calendar.YEAR);
        mEMonth = c.get(Calendar.MONTH);
        mEDay = c.get(Calendar.DAY_OF_MONTH);
        mEHour = c.get(Calendar.HOUR);
        mEMinute = c.get(Calendar.MINUTE);
        pEndHour = c.get(Calendar.HOUR_OF_DAY);*/

        String stDate = null;



        final Calendar c = Calendar.getInstance();
        c.setTime(new Date(startDate + " " + startTime));
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mHour = c.get(Calendar.HOUR);
        mMinute = c.get(Calendar.MINUTE);
        pStartHour = c.get(Calendar.HOUR_OF_DAY);

        mEYear = c.get(Calendar.YEAR);
        mEMonth = c.get(Calendar.MONTH);
        mEDay = c.get(Calendar.DAY_OF_MONTH);
        mEHour = c.get(Calendar.HOUR);
        mEMinute = c.get(Calendar.MINUTE);
        pEndHour = c.get(Calendar.HOUR_OF_DAY);



        if (stDate != null && stDate.length() > 0)
            btnToTime.setText(stDate);
        else {

            Format formatter;
            SimpleDateFormat df = new SimpleDateFormat("hh:mm");
            Date d=null;
            try {
                d = df.parse(mHour + ":" + mMinute);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Calendar gc = new GregorianCalendar();
            gc.setTime(d);
            gc.add(Calendar.MINUTE, 30);
            Date d2 = gc.getTime();
            formatter = new SimpleDateFormat("hh:mm a");
            String time = formatter.format(d2);
            btnToTime.setText(time);
            //venkat
            Log.d("inide else--->", time);
        }

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        v.getId();
        Log.d("START END", "View ID" + v.getId());
        if (v == btnFromDate) {
            showDialog(DATE_DIALOG_ID);

        } else if (v == btnFromTime) {
            showDialog(TIME_DIALOG_ID);
        } else if (v == btnToDate) {
            showDialog(END_DATE_DIALOG_ID);
        } else if (v == btnToTime) {
            showDialog(END_TIME_DIALOG_ID);
        }
        switch (v.getId()) {
        case R.id.chAlldays:
            if (((CheckBox) v).isChecked()) {

                btnToTime.setVisibility(View.GONE);
                btnFromTime.setVisibility(View.GONE);
                btnFromTime.setText("12:00 AM");
                btnToTime.setText("11:59 PM");

            } else {
                btnToTime.setVisibility(View.VISIBLE);
                btnFromTime.setVisibility(View.VISIBLE);
            }

            break;
        case R.id.btnStartEndBack:
            String location = new String();
            location = "";

            Intent backMeetingIntent = new Intent(this, NewMeeting.class);
            backMeetingIntent.putExtra("2", location);
            setResult(RESULT_OK, backMeetingIntent);
            finish();

            break;

        case R.id.btnStartEndDone:
            try {
                String startDate = new String();
                String startTime = new String();
                String endDate = new String();
                String endTime = new String();

                IsAllDay = chAlldays.isChecked();

                Intent insertIntent = new Intent(this, NewMeeting.class);
                if (btnFromDate.getText() != null
                        && btnFromDate.getText().toString().length() > 0)
                    startDate = btnFromDate.getText().toString();
                if (btnFromTime.getText() != null
                        && btnFromTime.getText().toString().length() > 0)
                    startTime = btnFromTime.getText().toString();
                if (btnToDate.getText() != null
                        && btnToDate.getText().toString().length() > 0)
                    endDate = btnToDate.getText().toString();
                if (btnToTime.getText() != null
                        && btnToTime.getText().toString().length() > 0)
                    endTime = btnToTime.getText().toString();

                Date dateStart = null;
                Date dateEnd = null;

                if(chAlldays.isChecked()){
                    dateStart = new Date(startDate);
                    dateEnd = new Date(endDate);
                }else{
                    dateStart = new Date(startDate + " " + startTime);
                    dateEnd = new Date(endDate + " " + endTime);
                }

                Log.d("GS startDate", dateStart+"");
                Log.d("GS endDate", dateEnd+"");

                //venkat
                Calendar current = Calendar.getInstance();

                int cHour = current.get(Calendar.HOUR);
                int cMinute = current.get(Calendar.MINUTE);
                //Log.d("currentTime in StartEndActivity--->",cHour+""+cMinute);
                String time = currentTimeDisplay(cHour, cMinute);
                //Log.d("selectedTime in StartEndActivity--->",btnFromTime.getText().toString());
                Collator myCollator = Collator.getInstance(); 

                Log.d("test in StartEndActivity--->", myCollator.compare(time, btnFromTime.getText().toString()) +"");
                if (dateStart.equals(current.getTime())
                        || dateEnd.equals(current.getTime())
                        || dateStart.before(current.getTime())
                        || dateEnd.before(current.getTime())) {
                    AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
                    alertbox.setMessage("Start Date/Time should be greater than current Date/Time");
                    alertbox.setNeutralButton("Ok",
                            new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface arg0,
                                int arg1) {
                        }
                    });
                    alertbox.show();

                }else if(dateStart.equals(dateEnd)){
                    AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
                    alertbox.setMessage("Start and End Date/Time should not be same");
                    alertbox.setNeutralButton("Ok",
                            new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface arg0,
                                int arg1) {
                        }
                    });
                    alertbox.show();
                } else if(dateStart.before(dateEnd)) {
                    insertIntent.putExtra("1", startDate);
                    insertIntent.putExtra("2", startTime);
                    insertIntent.putExtra("3", endDate);
                    insertIntent.putExtra("4", endTime);
                    insertIntent.putExtra("IsAllDay", IsAllDay);
                    setResult(RESULT_OK, insertIntent);
                    finish();
                }else if(dateStart.after(dateEnd)){
                    AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
                    alertbox.setMessage("End date/time should be greater than Start date/time");
                    alertbox.setNeutralButton("Ok",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface arg0,
                                        int arg1) {
                                }
                            });
                    alertbox.show();

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //venkat
    private String currentTimeDisplay(int hour, int minutes) {

        try {
            Format formatter;
            SimpleDateFormat df = new SimpleDateFormat("hh:mm");
            Date d = df.parse(hour + ":" + minutes);
            Calendar gc = new GregorianCalendar();
            gc.setTime(d);
            gc.add(Calendar.HOUR, 0);
            gc.add(Calendar.MINUTE,0);
            Date d2 = gc.getTime();
            formatter = new SimpleDateFormat("hh:mm a");
            String time = formatter.format(d2);
            Log.d("currentTime in StartEndActivity--->",time);
            return time;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }


    private void updateEndTimeDisplay() {

        try {
            Format formatter;
            SimpleDateFormat df = new SimpleDateFormat("hh:mm");
            Date d = df.parse(mEHour + ":" + mEMinute);
            Calendar gc = new GregorianCalendar();
            gc.setTime(d);
            gc.add(Calendar.HOUR, 0);
            Date d2 = gc.getTime();
            formatter = new SimpleDateFormat("hh:mm a");
            String time = formatter.format(d2);
            btnToTime.setText(time);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void updateTimeDisplay() {

        try {
            Format formatter;
            SimpleDateFormat df = new SimpleDateFormat("hh:mm");
            Date d = df.parse(mHour + ":" + mMinute);
            Calendar gc = new GregorianCalendar();
            gc.setTime(d);
            gc.add(Calendar.HOUR, 0);
            Date d2 = gc.getTime();
            formatter = new SimpleDateFormat("hh:mm a");
            String time = formatter.format(d2);

            btnFromTime.setText(time);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void updateEndDisplay() {

        java.util.Date dt = new java.util.Date(mEYear - 1900, mEMonth, mEDay);
        SimpleDateFormat dateFormatter = new SimpleDateFormat(
                "EEE, MMM dd, yyyy");
        btnToDate.setText(dateFormatter.format(dt));

    }

    private void updateStartDisplay() {

        java.util.Date dt = new java.util.Date(mYear - 1900, mMonth, mDay);
        SimpleDateFormat dateFormatter = new SimpleDateFormat(
                "EEE, MMM dd, yyyy");
        btnFromDate.setText(dateFormatter.format(dt));

    }

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

        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            updateStartDisplay();
        }
    };
    private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            mHour = hourOfDay;
            mMinute = minute;
            if(mHour==12)
                btnFromTime.setText(new StringBuilder().append("12").append(":").append(pad(minute)+" PM"));
        else
            updateTimeDisplay();
        }
    };
    private DatePickerDialog.OnDateSetListener endDateSetListener = new DatePickerDialog.OnDateSetListener() {

        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            mEYear = year;
            mEMonth = monthOfYear;
            mEDay = dayOfMonth;
            updateEndDisplay();
        }
    };
    private TimePickerDialog.OnTimeSetListener endTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute ) {
            mEHour = hourOfDay;
            mEMinute = minute;
            if(mEHour==12)
                btnToTime.setText(new StringBuilder().append("12").append(":").append(pad(minute)+" PM"));
        else
            updateEndTimeDisplay();
        }
    };

    @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, pStartHour, mMinute,
                    false);
        case END_DATE_DIALOG_ID:
            return new DatePickerDialog(this, endDateSetListener, mEYear,
                    mEMonth, mEDay);
        case END_TIME_DIALOG_ID:
            mEMinute+=30;
            if(mEMinute>60){
                pEndHour ++;
                mEMinute =  mEMinute-60;
            }
            return new TimePickerDialog(this, endTimeSetListener, pEndHour,
                    mEMinute, false);
        }
        return null;
    }
    public  String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);

    }

}

答案 1 :(得分:1)

如果要在应用程序中使用DatePicker显示多个日期,则无需使用两次DATE_DIALOG_ID。您只能使用一个并满足您的要求。我在这里贴了代码,希望它能帮到你。

在按钮中单击

btnFromDate.setOnClickListener(clkListener);
btnToDate.setOnClickListener(clkListener);

然后

public OnClickListener clkListener = new OnClickListener()
    {
        @Override
        public void onClick(View v) 
        {
            if(v == btnFromDate)
            {
                showDateDialog(editTextFromDate, Calendar.getInstance());
            }
            if(v == btnToDate)
            {
                showDateDialog(editTextToDate, Calendar.getInstance());
            }
                }
   };

然后

EditText activeDateDisplay ;
Calendar activeDate;

public void showDateDialog(EditText dateDisplay, Calendar date) 
    {
        activeDateDisplay = dateDisplay;
        activeDate = date;
        showDialog(DATE_DIALOG_ID);
    }

然后

 CharSequence strFormate_Date;
 int DATE_DIALOG_ID = 0;

@Override
    protected Dialog onCreateDialog(int id) 
    {
        switch (id) 
        {
            case DATE_DIALOG_ID:
            {
                return new DatePickerDialog(Activity.this, mDateSetListener, activeDate.get(Calendar.YEAR), activeDate.get(Calendar.MONTH), activeDate.get(Calendar.DAY_OF_MONTH));
            }
        }
        return null;
    }

    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() 
    {
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) 
        {
            activeDate.set(Calendar.YEAR, year);
            activeDate.set(Calendar.MONTH, monthOfYear);
            activeDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateDisplay(activeDateDisplay, activeDate);
            unregisterDateDisplay();
        }
    };
    private void unregisterDateDisplay() 
    {
        activeDateDisplay = null;
        activeDate = null;
        strFormate_Date = null;
    }

    private void updateDisplay(EditText dateDisplay, Calendar date) 
    {
        Time chosenDate = new Time();
        chosenDate.set(date.get(Calendar.DAY_OF_MONTH), date.get(Calendar.MONTH), date.get(Calendar.YEAR));
        long dtDob = chosenDate.toMillis(true);
        strFormate_Date = DateFormat.format("dd/MM/yyyy", dtDob);
        dateDisplay.setText(""+strFormate_Date);
    }

我希望它能解决你的问题。如果你有任何问题,那么你可以问我。

答案 2 :(得分:0)

 public class DateTimepickerActivity extends Activity {
/** Called when the activity is first created. */

Button btnFromDate=(Button) findViewById(R.id.btnFromDate) ;
Button btnToDate =(Button) findViewById(R.id.btnToDate);

EditText editTextFromDate=(EditText) findViewById(R.id.btnFromDate);
EditText editTextToDate =  (EditText) findViewById(R.id.btnToDate);

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


    btnFromDate.setOnClickListener(clkListener);
    btnToDate.setOnClickListener(clkListener);



   }

  public OnClickListener clkListener = new OnClickListener()
    {
    @Override
    public void onClick(View v) 
    {
        if(v == btnFromDate)
        {
            showDateDialog(editTextFromDate, Calendar.getInstance());
        }
        if(v == btnToDate)
        {
            showDateDialog(editTextToDate, Calendar.getInstance());
        }
            }
        };


   EditText activeDateDisplay ;
   Calendar activeDate;

    public void showDateDialog(EditText dateDisplay, Calendar date) 
   {
       activeDateDisplay = dateDisplay;
       activeDate = date;
       showDialog(DATE_DIALOG_ID);
   }


   CharSequence strFormate_Date;
   int DATE_DIALOG_ID = 0;

  @Override
  protected Dialog onCreateDialog(int id) 
  {
      switch (id) 
      {
          case DATE_DIALOG_ID:
          {
              return new DatePickerDialog(Activity.this, mDateSetListener, 
         activeDate.get(Calendar.YEAR), activeDate.get(Calendar.MONTH), 
         activeDate.get(Calendar.DAY_OF_MONTH));

          }
        }
      return null;
  }

  private DatePickerDialog.OnDateSetListener mDateSetListener = new 
  DatePickerDialog.OnDateSetListener() 
  {
      public void onDateSet(DatePicker view, int year, int monthOfYear, int 
      dayOfMonth) 
      {
          activeDate.set(Calendar.YEAR, year);
          activeDate.set(Calendar.MONTH, monthOfYear);
          activeDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
          updateDisplay(activeDateDisplay, activeDate);
          unregisterDateDisplay();
      }
  };
  private void unregisterDateDisplay() 
  {
      activeDateDisplay = null;
      activeDate = null;
      strFormate_Date = null;
  }

  private void updateDisplay(EditText dateDisplay, Calendar date) 
  {
      Time chosenDate = new Time();
      chosenDate.set(date.get(Calendar.DAY_OF_MONTH), date.get(Calendar.MONTH), 
   date.get(Calendar.YEAR));
      long dtDob = chosenDate.toMillis(true);
      strFormate_Date = DateFormat.format("dd/MM/yyyy", dtDob);
      dateDisplay.setText(""+strFormate_Date);
  }