1

我在屏幕上有 2 个日期选择器和 2 个时间选择器,还有一个提交按钮。用户选择开始日期、开始时间、结束日期和结束时间。然后程序获取这些值并将它们存储到变量中,但是变量只返回这些控件的默认值。有没有办法从这些控件中的每一个中获取更新的值?

我的代码在编辑屏幕上看起来像这样:

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));
}
4

2 回答 2

1

改写

查看您当前的代码,让我们继续使用getDatePicker 和 TimePicker 中的各种方法。但是,您从不打电话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
}
于 2012-10-19T23:48:58.120 回答
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 
        }
    }); 
于 2012-10-20T03:14:06.907 回答