3

如何在 TimePicker 中设置先前选择的值?

我的意思是,单击 TextView,出现 TimePicker 对话框,然后我选择时间并将其设置在 TextView 中,例如 TextView 上的 12:30 PM。

之后,如果我想更改时间,请再次单击 TextView,然后 TimePicker 对话框应显示先前选择的值。所以 TimePicker 应该显示 12:30 PM。

我怎样才能做到这一点?

4

1 回答 1

3

如果您使用 onCreateDialog 创建时间选择器对话框并调用它,它将自动存储以前的值。

@Override
protected Dialog onCreateDialog(int id) {

switch (id) {

    case 0:

TimePickerDialog timeDlg = new TimePickerDialog(this,
                new TimePickerDialog.OnTimeSetListener() {

                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay,
                            int minute) {
                        // TODO Auto-generated method stub

                        if (hourOfDay > 12) {
                            hourOfDay = hourOfDay - 12;
                            time = " PM";
                        } else if (hourOfDay < 12 && hourOfDay != 0) {
                            time = " AM";
                        } else if (hourOfDay == 12) {
                            time = " PM";
                        } else if (hourOfDay == 0) {
                            hourOfDay = 12;
                            time = " AM";
                        }

                        Toast.makeText(
                                getApplicationContext(),
                                new StringBuilder().append(pad(hourOfDay))
                                        .append(":").append(pad(minute))
                                        .append(time), Toast.LENGTH_SHORT)
                                .show();
                    }
                }, 12, 00, false);

        timeDlg.setMessage("Set Time:");

        timeDlg.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "Dismiss",
                        Toast.LENGTH_SHORT).show();
            }
        });
        return timeDlg;
}
    return null;
}

使用 showDialog(id); 显示对话框。

于 2012-05-01T13:26:33.020 回答