samurai
samurai

Reputation: 101

android studio clock set time only show 0 or 30

I use android write to set time, I use edittext, when I click ,it will show clock TimePickerDialog, how can I only show 0 and 30 on my clock? but I have some limit
I hope my hour just can set AM8-17,and minute just can set 00 or 30
EX:8:30 / 14:00..... I don't know how to do it, can someone help me? thanks.
this is my code,

    time2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
                showtime2();
            }
        }
    });
 private void showtime2() {
    Calendar c = Calendar.getInstance();
    new TimePickerDialog(Off.this, R.style.DatePickBackgroundColor2, new 
TimePickerDialog.OnTimeSetListener(){

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            String tmp="",tmp2="";
            if(hourOfDay<10){tmp="0"+hourOfDay;}else tmp=""+hourOfDay;
            if(minute<10){tmp2="0"+minute;}else tmp2=""+minute;
            time2.setText(tmp + ":" + tmp2);
        }
    },  c.get(Calendar.HOUR), c.get(Calendar.MINUTE), false).show();
}

This is my clock picture

Upvotes: 1

Views: 772

Answers (1)

Yunus Karaaslan
Yunus Karaaslan

Reputation: 304

Let us say you have a time picker in your xml file like the one below, pay attention to using spinner as the time picker's mode so that you can show TimePicker with intervals:

<TimePicker
    android:id="@+id/timepicker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:timePickerMode="spinner"/>

Set setIs24HourView() to true in order to get rid of am/pm and call a function in which you will set the displayable value.

TimePicker timepicker = findViewById(R.id.timepicker);
timepicker.is24HourView();
setInterval(timepicker);

Finally, the setInterval() function should be like this depending on your need:

private void setInterval(TimePicker timePicker) {
        try {

            NumberPicker minutePicker = timePicker.findViewById(Resources.getSystem().getIdentifier(
                    "minute", "id", "android"));

            String[] display = new String[] { "0", "30" };

            minutePicker.setMinValue(0);
            minutePicker.setMaxValue(display.length - 1);
            minutePicker.setDisplayedValues(display);
        } catch (Exception ex) {
            Log.d(TAG, ex.getMessage());
        }
    }

Upvotes: 1

Related Questions