如何简单地存储选定的时间从Android中的TimePicker那个值我在edittext中打算?

时间:2014-07-25 08:17:03

标签: android android-timepicker

我想从android中的Time-picker中检索时间并存储在适当的变量中,哪个变量适合它。如何以简单的方式检索用户选择的时间。

我在编辑文本上获得了时间选择器的价值,但我应该如何在适当的变量中获取它。

这是我的javacode: -

                    et = (EditText) findViewById(R.id.amar);
            et.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            Calendar mcurrentTime = Calendar.getInstance();
                            int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
                            int minute = mcurrentTime.get(Calendar.MINUTE);
                            TimePickerDialog mTimePicker;
                            mTimePicker = new TimePickerDialog(Timepicker.this,
                                    new TimePickerDialog.OnTimeSetListener() {
                                        @Override
                                        public void onTimeSet(TimePicker timePicker,
                                                int selectedHour, int selectedMinute) {
                                            et.setText(selectedHour + ":" + selectedMinute);
                                        }
                                    }, hour, minute, false);// Yes 24 hour time
                            mTimePicker.setTitle("Select Starting Time");
                            mTimePicker.show();
                        }
                    });

1 个答案:

答案 0 :(得分:1)

您应该再次获取当前时间,而不是使用et.setText(),只需将小时和分钟属性修改为新选择的属性。

    Calendar initialTime = Calendar.getInstance();

    int hour = initialTime.get(Calendar.HOUR_OF_DAY);
    int minute = initialTime.get(Calendar.MINUTE);

    TimePickerDialog mTimePicker = new TimePickerDialog(Timepicker.this,
        new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker,
                    int selectedHour, int selectedMinute) {

                Calendar currentTime = Calendar.getInstance();
                currentTime.set(Calendar.HOUR_OF_DAY, selectedHour);
                currentTime.set(Calendar.MINUTE, selectedMinute);

                Date selectedDate = currentTime.getTime();
            }
        }, hour, minute, false);// Yes 24 hour time

    mTimePicker.setTitle("Select Starting Time");
    mTimePicker.show();

希望有所帮助