如何使用timepicker dialogFragment android

时间:2015-10-13 06:47:07

标签: java timepicker

我想限制timepicker中的时间范围。为此,我需要在TimePickerDialog Fragment中设置最小和最大时间。我已经搜索了许多网站这个简单的问题,但我没有得到任何正确的解决方案。我只为datepicker和数字选择器获得解决方案。任何帮助将是欣赏。

我使用了以下代码:

    public class TimePickerDialogFragment extends DialogFragment {

    public static final String TIME_IN_MILLIS = "com.iandmydoctor.android.utils.TIME_IN_MILLIS";

    private OnTimeSetListener mTimeSetCallback;
    private boolean is24HourView = false;

    public TimePickerDialogFragment() {
    }

    public void setOnTimeSetListener(OnTimeSetListener listener) {
        mTimeSetCallback = listener;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Bundle b = getArguments();
        Calendar c = Calendar.getInstance();
        long time = b.getLong(TIME_IN_MILLIS);

        if (time < System.currentTimeMillis()) {
            time = System.currentTimeMillis();
        }

        c.setTimeInMillis(time);
        int mHour = c.get(Calendar.HOUR_OF_DAY);
        int mMinute = c.get(Calendar.MINUTE);

        TimePickerDialog.OnTimeSetListener listener = new TimePickerDialog.OnTimeSetListener() {
            boolean fired = false;

            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                if (fired) {
                    return;
                }
                fired = true;
                if (mTimeSetCallback != null) {
                    mTimeSetCallback.onTimeSet(hourOfDay, minute);
                }
            }
        };


        return new TimePickerDialog(getActivity(), listener, mHour, mMinute, is24HourView);
    }



    public void setIs24HourView(boolean is24HourView) {
        this.is24HourView = is24HourView;
    }

    public interface OnTimeSetListener {
        void onTimeSet(int hourOfDay, int minute);
    }

}

在我的活动中:

  private void showTimePickerDialog(long timeInMillis, TimePickerDialogFragment.OnTimeSetListener listener) {
    Bundle args = new Bundle();
    args.putLong(TimePickerDialogFragment.TIME_IN_MILLIS, timeInMillis);
    TimePickerDialogFragment timePicker = new TimePickerDialogFragment();
    timePicker.setArguments(args);
    timePicker.setOnTimeSetListener(listener);
    timePicker.show(getSupportFragmentManager(), "time_picker");
}

0 个答案:

没有答案