2

我想在我的活动中有一个按钮,该按钮将默认当前日期显示为按钮标题,当我单击按钮以显示日期选择器对话框并将新选择显示为按钮标题时。

我怎样才能做到这一点?有更好的主意吗?最好用 EditText 来做到这一点,以便用户更容易更改日期?

4

1 回答 1

1

我在这里附上了时间和日期的代码,根据您的要求使用它。这里打算 txtdate 和 txtTime 你可以在按钮文本上设置它。

private static final int DIALOG_DATE = 1;
         private static final int DIALOG_TIME = 2;    


private Calendar dateTime = Calendar.getInstance();
     private SimpleDateFormat dateFormatter = new SimpleDateFormat(
             "MMMM dd yyyy");
     private SimpleDateFormat timeFormatter = new SimpleDateFormat(
             "hh:mm a");


                 txtstdate.setText(dateFormatter.format(dateTime.getTime()));   
  txtAddtime.setText(timeFormatter.format(dateTime.getTime()));


@Override
    protected Dialog onCreateDialog(int id)
    {
        switch (id)
        {
        case DIALOG_DATE:
            return new DatePickerDialog(this, new OnDateSetListener()
            {

                @Override
                public void onDateSet(DatePicker view, int year,
                        int monthOfYear, int dayOfMonth)
                {
                    dateTime.set(year, monthOfYear, dayOfMonth);
                    txtstdate.setText(dateFormatter.format(dateTime.getTime()));
                    txtAdddate.setText(dateFormatter.format(dateTime.getTime()));
                }
            }, dateTime.get(Calendar.YEAR),
               dateTime.get(Calendar.MONTH),
               dateTime.get(Calendar.DAY_OF_MONTH));

        case DIALOG_TIME:
            return new TimePickerDialog(this, new OnTimeSetListener()
            {

                @Override
                public void onTimeSet(TimePicker view, int hourOfDay,
                        int minute)
                {
                    dateTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
                    dateTime.set(Calendar.MINUTE, minute);
                    txtsttime.setText(timeFormatter.format(dateTime.getTime()));
                    txtAddtime.setText(timeFormatter.format(dateTime.getTime()));
                }
            }, dateTime.get(Calendar.HOUR_OF_DAY),
               dateTime.get(Calendar.MINUTE), false);

        }
        return null;
    }


}

**Call Dialog:**    

在按钮单击事件上调用此方法。

showDialog(DIALOG_DATE);

showDialog(DIALOG_TIME);

访问更多参考:http ://hasmukhbhadani.blogspot.in/search/label/Date%20and%20time%20Dialog 。 http://hasmukhbhadani.blogspot.in/search/label/DatePickerSlider%20in%20android

于 2012-09-07T11:10:43.090 回答