2012-09-07 225 views
2

我想在我的活動中顯示一個按鈕,該按鈕將當前日期顯示爲按鈕標題,當我單擊按鈕以顯示日期選擇器對話框並顯示新的選擇按鈕標題。如何在一個按鈕中選擇日期選擇器+顯示日期android

我該如何做到這一點?任何更好的主意?最好是用EditText做這件事,以便讓用戶更容易地改變日期?

+1

按照本教程http://www.mkyong.com/android/android-date-picker-example/ –

回答

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

相關問題