2012-10-19 147 views
1

我在屏幕上還有2個日期選擇器和2個時間選擇器,還有一個提交按鈕。用戶選擇開始日期,開始時間,結束日期和結束時間。然後程序取這些值並將它們存儲到變量中,但變量僅返回這些控件的默認值。無論如何要從每個這些控件獲取更新的值?從DatePicker和TimePicker獲取值

我的代碼看起來像這樣的編輯屏幕:

public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.editscreen); 

    timepickerStart = (TimePicker)findViewById(R.id.timePicker1); 
    timepickerEnd = (TimePicker)findViewById(R.id.timePicker2); 
    datepickerStart = (DatePicker)findViewById(R.id.datePicker1); 
    datepickerEnd = (DatePicker)findViewById(R.id.datePicker2); 

    submitbutton = (Button)findViewById(R.id.submit); 

    locationText = (EditText)findViewById(R.id.locationText); 
    eventText = (EditText)findViewById(R.id.eventText); 

} 

public void DateStart(View v) 
{ 
    GlobalVariables.datepickerYearStart = datepickerStart.getYear(); 
    GlobalVariables.datepickerMonthStart = datepickerStart.getMonth(); 
    GlobalVariables.datepickerDayStart = datepickerStart.getDayOfMonth(); 
} 

public void DateEnd(View v) 
{ 
    GlobalVariables.datepickerYearEnd = datepickerEnd.getYear(); 
    GlobalVariables.datepickerMonthEnd = datepickerEnd.getMonth(); 
    GlobalVariables.datepickerDayEnd = datepickerEnd.getDayOfMonth(); 
} 

public void TimeStart(View v) 
{ 
    GlobalVariables.timepickerHourStart = timepickerStart.getCurrentHour(); 
    GlobalVariables.timepickerMinuteStart = timepickerStart.getCurrentMinute(); 
} 

public void TimeEnd(View v) 
{ 
    GlobalVariables.timepickerHourEnd = timepickerEnd.getCurrentHour(); 
    GlobalVariables.timepickerMinuteEnd = timepickerEnd.getCurrentMinute(); 
} 

public void submitClicked(View v) 
{ 

    startActivity(new Intent(this, AddToCalendar.class)); 
} 

回答

1

重寫

看你當前的代碼,讓我們堅持從的DatePicker和TimePicker各種get方法。但是你永遠不會調用DateStart()或任何其他人的時候,看起來就像你有他們設置了一個OnClickListener ......不管怎樣,試試這個:

public void submitClick(View v) { 
    DateStart(null); 
    TimeStart(null); 
    DateEnd(null); 
    TimeEnd(null); 

    // Do what you please your GlobalVariables 
} 

雖然我可以離開了多個GlobalVariables和存儲每個日期/時間爲一個long值:

public void submitClick(View v) { 
    Calendar calendar = Calendar.getInstance(); 
    calendar.set(datepickerStart.getYear(), datepickerStart.getMonth(), 
       datepickerStart.getDayOfMonth(), timepickerStart.getCurrentHour(), 
       timepickerStart.getCurrentMinute(), 0); 
    long startTime = calendar.getTimeInMillis(); 

    // And similar approach for the end time, then use them however you please 
} 
+0

如何在這種情況下使用OnDateChanged和OnTimeChanged。我能找到的唯一例子是使用DialogBoxPopup,這是我不想使用的。 – Palagerini

1

您需要設置一個監聽到你的DatePicker:

DatePicker picker = new DatePicker(this); 
    picker.init(<year>, <monthOfYear>, <dayOfMonth>, new DatePicker.OnDateChangedListener() { 

     @Override 
     public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { 
      //set the value of the variable here 
     } 
    });