如何在按钮中选择日期+显示日期?android

时间:2012-09-07 10:56:31

标签: android layout button datepicker textview

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

我如何实现这一目标?更好的想法?使用EditText更好地为用户提供更改日期的方法吗?

1 个答案:

答案 0 :(得分: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%20Dialoghttp://hasmukhbhadani.blogspot.in/search/label/DatePickerSlider%20in%20android