Material Time Picker Dialog in Android – Coding Shiksha

Material Time Picker Dialog in Android – Coding Shiksha

Welcome Folks I am back with another blog post. In this post I will be showing how to make a material dialog time picker in android.

 

Include the Library

 

dependencies {
    implementation 'com.wdullaer:materialdatetimepicker:4.2.0'
}

 

Demo

 

 

 

 

 

 

 

Example Code

 

TimePickerFragment.java

 

package com.wdullaer.datetimepickerexample;

import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import com.wdullaer.materialdatetimepicker.time.Timepoint;

import java.util.Calendar;

/**
 * A simple {@link Fragment} subclass.
 */
public class TimePickerFragment extends Fragment implements TimePickerDialog.OnTimeSetListener {

    private TextView timeTextView;
    private CheckBox mode24Hours;
    private CheckBox modeDarkTime;
    private CheckBox modeCustomAccentTime;
    private CheckBox vibrateTime;
    private CheckBox dismissTime;
    private CheckBox titleTime;
    private CheckBox enableSeconds;
    private CheckBox limitSelectableTimes;
    private CheckBox disableSpecificTimes;
    private CheckBox showVersion2;
    private TimePickerDialog tpd;

    public TimePickerFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.timepicker_layout, container, false);

        // Find our View instances
        timeTextView = view.findViewById(R.id.time_textview);
        Button timeButton = view.findViewById(R.id.time_button);
        mode24Hours = view.findViewById(R.id.mode_24_hours);
        modeDarkTime = view.findViewById(R.id.mode_dark_time);
        modeCustomAccentTime = view.findViewById(R.id.mode_custom_accent_time);
        vibrateTime = view.findViewById(R.id.vibrate_time);
        dismissTime = view.findViewById(R.id.dismiss_time);
        titleTime = view.findViewById(R.id.title_time);
        enableSeconds = view.findViewById(R.id.enable_seconds);
        limitSelectableTimes = view.findViewById(R.id.limit_times);
        disableSpecificTimes = view.findViewById(R.id.disable_times);
        showVersion2 = view.findViewById(R.id.show_version_2);

        view.findViewById(R.id.original_button).setOnClickListener(view1 -> {
            Calendar now = Calendar.getInstance();
            new android.app.TimePickerDialog(
                    getActivity(),
                    (view11, hour, minute) -> Log.d("Original", "Got clicked"),
                    now.get(Calendar.HOUR_OF_DAY),
                    now.get(Calendar.MINUTE),
                    mode24Hours.isChecked()
            ).show();
        });

        // Show a timepicker when the timeButton is clicked
        timeButton.setOnClickListener(v -> {
            Calendar now = Calendar.getInstance();
            /*
            It is recommended to always create a new instance whenever you need to show a Dialog.
            The sample app is reusing them because it is useful when looking for regressions
            during testing
             */
            if (tpd == null) {
                tpd = TimePickerDialog.newInstance(
                        TimePickerFragment.this,
                        now.get(Calendar.HOUR_OF_DAY),
                        now.get(Calendar.MINUTE),
                        mode24Hours.isChecked()
                );
            } else {
                tpd.initialize(
                        TimePickerFragment.this,
                        now.get(Calendar.HOUR_OF_DAY),
                        now.get(Calendar.MINUTE),
                        now.get(Calendar.SECOND),
                        mode24Hours.isChecked()
                );
            }
            tpd.setThemeDark(modeDarkTime.isChecked());
            tpd.vibrate(vibrateTime.isChecked());
            tpd.dismissOnPause(dismissTime.isChecked());
            tpd.enableSeconds(enableSeconds.isChecked());
            tpd.setVersion(showVersion2.isChecked() ? TimePickerDialog.Version.VERSION_2 : TimePickerDialog.Version.VERSION_1);
            if (modeCustomAccentTime.isChecked()) {
                tpd.setAccentColor(Color.parseColor("#9C27B0"));
            }
            if (titleTime.isChecked()) {
                tpd.setTitle("TimePicker Title");
            }
            if (limitSelectableTimes.isChecked()) {
                if (enableSeconds.isChecked()) {
                    tpd.setTimeInterval(3, 5, 10);
                } else {
                    tpd.setTimeInterval(3, 5, 60);
                }
            }
            if (disableSpecificTimes.isChecked()) {
                Timepoint[] disabledTimes = {
                        new Timepoint(10),
                        new Timepoint(10, 30),
                        new Timepoint(11),
                        new Timepoint(12, 30)
                };
                tpd.setDisabledTimes(disabledTimes);
            }
            tpd.setOnCancelListener(dialogInterface -> {
                Log.d("TimePicker", "Dialog was cancelled");
                tpd = null;
            });
            tpd.show(requireFragmentManager(), "Timepickerdialog");
        });

        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        tpd = null;
    }

    @Override
    public void onResume() {
        super.onResume();
        TimePickerDialog tpd = (TimePickerDialog) requireFragmentManager().findFragmentByTag("Timepickerdialog");
        if(tpd != null) tpd.setOnTimeSetListener(this);
    }

    @Override
    public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
        String hourString = hourOfDay < 10 ? "0"+hourOfDay : ""+hourOfDay;
        String minuteString = minute < 10 ? "0"+minute : ""+minute;
        String secondString = second < 10 ? "0"+second : ""+second;
        String time = "You picked the following time: "+hourString+"h"+minuteString+"m"+secondString+"s";
        timeTextView.setText(time);
        tpd = null;
    }
}

 

READ  Firebase Google Login in Android (Part-1) Demo

DatePickerFragment.java

 

package com.wdullaer.datetimepickerexample;

import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;

import java.util.Calendar;

/**
 * A simple {@link Fragment} subclass.
 */
public class DatePickerFragment extends Fragment implements DatePickerDialog.OnDateSetListener {

    private TextView dateTextView;
    private CheckBox modeDarkDate;
    private CheckBox modeCustomAccentDate;
    private CheckBox vibrateDate;
    private CheckBox dismissDate;
    private CheckBox titleDate;
    private CheckBox showYearFirst;
    private CheckBox showVersion2;
    private CheckBox switchOrientation;
    private CheckBox limitSelectableDays;
    private CheckBox highlightDays;
    private DatePickerDialog dpd;

    public DatePickerFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.datepicker_layout, container, false);

        // Find our View instances
        dateTextView = view.findViewById(R.id.date_textview);
        Button dateButton = view.findViewById(R.id.date_button);
        modeDarkDate = view.findViewById(R.id.mode_dark_date);
        modeCustomAccentDate = view.findViewById(R.id.mode_custom_accent_date);
        vibrateDate = view.findViewById(R.id.vibrate_date);
        dismissDate = view.findViewById(R.id.dismiss_date);
        titleDate = view.findViewById(R.id.title_date);
        showYearFirst = view.findViewById(R.id.show_year_first);
        showVersion2 = view.findViewById(R.id.show_version_2);
        switchOrientation = view.findViewById(R.id.switch_orientation);
        limitSelectableDays = view.findViewById(R.id.limit_dates);
        highlightDays = view.findViewById(R.id.highlight_dates);

        view.findViewById(R.id.original_button).setOnClickListener(v -> {
            Calendar now = Calendar.getInstance();
            new android.app.DatePickerDialog(
                    requireActivity(),
                    (view1, year, month, dayOfMonth) -> Log.d("Orignal", "Got clicked"),
                    now.get(Calendar.YEAR),
                    now.get(Calendar.MONTH),
                    now.get(Calendar.DAY_OF_MONTH)
            ).show();
        });

        // Show a datepicker when the dateButton is clicked
        dateButton.setOnClickListener(v -> {
            Calendar now = Calendar.getInstance();
            /*
            It is recommended to always create a new instance whenever you need to show a Dialog.
            The sample app is reusing them because it is useful when looking for regressions
            during testing
             */
            if (dpd == null) {
                dpd = DatePickerDialog.newInstance(
                        DatePickerFragment.this,
                        now.get(Calendar.YEAR),
                        now.get(Calendar.MONTH),
                        now.get(Calendar.DAY_OF_MONTH)
                );
            } else {
                dpd.initialize(
                        DatePickerFragment.this,
                        now.get(Calendar.YEAR),
                        now.get(Calendar.MONTH),
                        now.get(Calendar.DAY_OF_MONTH)
                );
            }
            dpd.setThemeDark(modeDarkDate.isChecked());
            dpd.vibrate(vibrateDate.isChecked());
            dpd.dismissOnPause(dismissDate.isChecked());
            dpd.showYearPickerFirst(showYearFirst.isChecked());
            dpd.setVersion(showVersion2.isChecked() ? DatePickerDialog.Version.VERSION_2 : DatePickerDialog.Version.VERSION_1);
            if (modeCustomAccentDate.isChecked()) {
                dpd.setAccentColor(Color.parseColor("#9C27B0"));
            }
            if (titleDate.isChecked()) {
                dpd.setTitle("DatePicker Title");
            }
            if (highlightDays.isChecked()) {
                Calendar date1 = Calendar.getInstance();
                Calendar date2 = Calendar.getInstance();
                date2.add(Calendar.WEEK_OF_MONTH, -1);
                Calendar date3 = Calendar.getInstance();
                date3.add(Calendar.WEEK_OF_MONTH, 1);
                Calendar[] days = {date1, date2, date3};
                dpd.setHighlightedDays(days);
            }
            if (limitSelectableDays.isChecked()) {
                Calendar[] days = new Calendar[13];
                for (int i = -6; i < 7; i++) {
                    Calendar day = Calendar.getInstance();
                    day.add(Calendar.DAY_OF_MONTH, i * 2);
                    days[i + 6] = day;
                }
                dpd.setSelectableDays(days);
            }
            if (switchOrientation.isChecked()) {
                if (dpd.getVersion() == DatePickerDialog.Version.VERSION_1) {
                    dpd.setScrollOrientation(DatePickerDialog.ScrollOrientation.HORIZONTAL);
                } else {
                    dpd.setScrollOrientation(DatePickerDialog.ScrollOrientation.VERTICAL);
                }
            }
            dpd.setOnCancelListener(dialog -> {
                Log.d("DatePickerDialog", "Dialog was cancelled");
                dpd = null;
            });
            dpd.show(requireFragmentManager(), "Datepickerdialog");
        });

        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dpd = null;
    }

    @Override
    public void onResume() {
        super.onResume();
        DatePickerDialog dpd = (DatePickerDialog) requireFragmentManager().findFragmentByTag("Datepickerdialog");
        if(dpd != null) dpd.setOnDateSetListener(this);
    }

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
        String date = "You picked the following date: "+dayOfMonth+"/"+(++monthOfYear)+"/"+year;
        dateTextView.setText(date);
        dpd = null;
    }
}

 

READ  How to Increase the Speed of Gradle in Android Studio

MainActivity.java

 

package com.wdullaer.datetimepickerexample;

import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

public class MainActivity extends AppCompatActivity
{
    ViewPager viewPager;
    PickerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        adapter = new PickerAdapter(getSupportFragmentManager());
        viewPager = findViewById(R.id.pager);
        viewPager.setAdapter(adapter);

        setSupportActionBar(findViewById(R.id.toolbar));
        TabLayout tabLayout = findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        for(int i=0; i < adapter.getCount(); i++) //noinspection ConstantConditions
            tabLayout.getTabAt(i).setText(adapter.getTitle(i));
    }

    private class PickerAdapter extends FragmentPagerAdapter {
        private static final int NUM_PAGES = 2;
        Fragment timePickerFragment;
        Fragment datePickerFragment;

        PickerAdapter(FragmentManager fm) {
            super(fm);
            timePickerFragment = new TimePickerFragment();
            datePickerFragment = new DatePickerFragment();
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }

        @Override
        public Fragment getItem(int position) {
            switch(position) {
                case 0:
                    return timePickerFragment;
                case 1:
                default:
                    return datePickerFragment;
            }
        }

        int getTitle(int position) {
            switch(position) {
                case 0:
                    return R.string.tab_title_time;
                case 1:
                default:
                    return R.string.tab_title_date;
            }
        }
    }
}

 

READ  Android Easy Runtime Permissions with Dexter

XML Code

 

datepicker_layout.xml

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <LinearLayout
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp">

        <!-- DatePicker Options -->
        <TextView
            android:id="@+id/date_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/selected_date"/>

        <Button
            android:id="@+id/date_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/pick_date"/>

        <Button
            android:id="@+id/original_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/original_button"/>

        <CheckBox
            android:id="@+id/show_version_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/show_version_2"/>

        <CheckBox
            android:id="@+id/mode_dark_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/mode_dark" />

        <CheckBox
            android:id="@+id/mode_custom_accent_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/mode_custom_accent" />

        <CheckBox
            android:id="@+id/vibrate_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/vibrate"
            android:checked="true"/>

        <CheckBox
            android:id="@+id/switch_orientation"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/switch_orientation" />

        <CheckBox
            android:id="@+id/dismiss_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/dismiss"
            android:checked="false"/>

        <CheckBox
            android:id="@+id/show_year_first"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/show_year_first"
            android:checked="false"/>

        <CheckBox
            android:id="@+id/title_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/title"
            android:checked="false"/>

        <CheckBox
            android:id="@+id/limit_dates"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/limit_dates"
            android:checked="false"/>

        <CheckBox
            android:id="@+id/highlight_dates"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/highlight_dates"
            android:checked="false"/>

    </LinearLayout>
</androidx.core.widget.NestedScrollView>

 

timepicker_layout.xml

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp">
        <!-- TimePicker options -->
        <TextView
            android:id="@+id/time_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/selected_time"/>

        <Button
            android:id="@+id/time_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/pick_time"/>

        <Button
            android:id="@+id/original_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/original_button"/>

        <CheckBox
            android:id="@+id/show_version_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/show_version_2"/>

        <CheckBox
            android:id="@+id/mode_24_hours"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/mode_24_hours" />

        <CheckBox
            android:id="@+id/mode_dark_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/mode_dark" />

        <CheckBox
            android:id="@+id/mode_custom_accent_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/mode_custom_accent" />

        <CheckBox
            android:id="@+id/vibrate_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/vibrate"
            android:checked="true"/>

        <CheckBox
            android:id="@+id/dismiss_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/dismiss"
            android:checked="false"/>

        <CheckBox
            android:id="@+id/title_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/title"
            android:checked="false"/>

        <CheckBox
            android:id="@+id/enable_seconds"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/enable_seconds"
            android:checked="false"/>

        <CheckBox
            android:id="@+id/limit_times"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/limit_times"
            android:checked="false"/>

        <CheckBox
            android:id="@+id/disable_times"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/disable_times"
            android:checked="false"/>

    </LinearLayout>
</androidx.core.widget.NestedScrollView>

 

activity_main.xml

 

<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:theme="@style/ThemeOverlay.AppCompat.Dark">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_height="?attr/actionBarSize"
            android:layout_width="match_parent"
            app:layout_scrollFlags="scroll|enterAlways"/>

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_height="wrap_content"
            android:layout_width="match_parent" />

    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/pager"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Leave a Reply

Close Menu