2012-10-19 146 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 
     } 
    });