使用edittext监听器在android中验证日期和时间

时间:2016-03-14 05:40:06

标签: android android-datepicker android-timepicker

我在点击编辑文字时遇到问题,我想点击编辑文字时会弹出日期和时间选择器对话框。请帮帮我。

public  void setstarttime()
    {
        startTimePicker = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker picker, int hourOfDay, int minute) {

                //set selected time to calender
                //@author om
                startTimeCal.set(Calendar.MINUTE, minute);
                startTimeCal.set(Calendar.HOUR, hourOfDay);

                mStartTimeHour = hourOfDay;
                mStartTimeMinute = minute;


                String am_pm = (hourOfDay < 12) ? "AM" : "PM";
                starttime.setText(CommonUtil.getFormattedTimeInString(startTimeCal.getTimeInMillis()) + " " + am_pm);
                // timeValidation(TAG_STARTTIME);
            }
        }, mStartTimeHour, mStartTimeMinute, false);
        startTimePicker.show();
    }

2 个答案:

答案 0 :(得分:1)

您应该实现OnFocusChangeListener

    EditText myEditText=......;
    myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus){
            // SHOW YOUR DIALOG
            }
        }
    });

答案 1 :(得分:0)

尝试使用以下代码:

timeEditText = (EditText) findViewById(R.id.timeEditText);
timeEditText.setFocusable(false);
timeEditText.setClickable(true);    

timeEditText.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Calendar mcurrentTime = Calendar.getInstance();
        final int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
        final int min = mcurrentTime.get(Calendar.MINUTE);
        TimePickerDialog mTimePicker;
        mTimePicker = new TimePickerDialog(v.getContext(), new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                String time = hourOfDay + ":" + minute;
                timeEditText.setText(time);
            }
        }, hour, min, true);

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