Android HorizontalDateTimepicker


This is an android horizontal datetimepicker tutorial and example.

We see how to create a horizontally scrolling datetime picker. You can easily scroll to a certain date.

The selected date gets shown in a Toast message.

We will be using HorizontalPicker Library.

HorizontalPicker is a custom-build Android View used for choosing dates (similar to the native date picker) but draws horizontally into a vertically narrow container. It allows easy day picking using the horizontal pan gesture.

Video Tutorial

Well we have a video tutorial as an alternative to this. If you prefer tutorials like this one then it would be good you subscribe to our YouTube channel. Basically we have a TV for programming where do daily tutorials especially android.

Features of HorizontalPicker

Here are some of the features of HorizontalPicker library:

  1. Date selection using a smooth swipe gesture
  2. Date selection by clicking on a day slot
  3. Date selection from code using the HorizontalPicker java object
  4. Month and year view
  5. Today button to jump to the current day
  6. Localized day and month names
  7. Configurable number of generated days (default: 120)
  8. Configurable number of offset generated days before the current date (default: 7)
  9. Customizable set of colors, or themed through the app theming engine

Dependencies of HorizontalPicker

To work with days, HorizontalPicker uses JodaTime library.

What is JodaTime

Joda-Time is a datetime library that provides a quality replacement for the Java date and time classes.

Joda-Time is the de facto standard date and time library for Java prior to Java SE 8.

Requirements

  1. Android 4.1 or later (Minimum SDK level 16)
  2. Android Studio (to compile and use)

How do we install and use HorizontalPicker?

In your app module’s Gradle config file, add the following dependency:

dependencies {
    implementation 'com.github.jhonnyx2012:horizontal-picker:1.0.6'
}

Then to include it into your layout, add the following:

<com.github.jhonnyx2012.horizontalpicker.HorizontalPicker
    android:id="@+id/datePicker"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

In your activity, you need to initialize it and set a listener, like this:

public class MainActivity extends AppCompatActivity implements DatePickerListener {
    @Override
    protected void onCreate(@Nullable final Bundle savedInstanceState) {
        // setup activity
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // find the picker
        HorizontalPicker picker = (HorizontalPicker) findViewById(R.id.datePicker);

        // initialize it and attach a listener
        picker
            .setListener(this)
            .init();
    }

    @Override
    public void onDateSelected(@NonNull final DateTime dateSelected) {
        // log it for demo
        Log.i("HorizontalPicker", "Selected date is " + dateSelected.toString());
    }
}

Finally, you can also configure the number of days to show, the date offset, or set a date directly to the picker. For all options, see the full configuration below.

    // at init time
    picker
        .setListener(listner)
        .setDays(20)
        .setOffset(10)
        .setDateSelectedColor(Color.DKGRAY)
        .setDateSelectedTextColor(Color.WHITE)
        .setMonthAndYearTextColor(Color.DKGRAY)
        .setTodayButtonTextColor(getColor(R.color.colorPrimary))
        .setTodayDateTextColor(getColor(R.color.colorPrimary))
        .setTodayDateBackgroundColor(Color.GRAY)
        .setUnselectedDayTextColor(Color.DKGRAY)
        .setDayOfWeekTextColor(Color.DKGRAY)
        .setUnselectedDayTextColor(getColor(R.color.textColor))
        .showTodayButton(false)
        .init();

    // or on the View directly after init was completed
    picker.setBackgroundColor(Color.LTGRAY);
    picker.setDate(new DateTime().plusDays(4));

Android HorizontalDateTimepicker Full Example

Lets look at a complete example.

Android HorizontalPicker

Tools

  1. IDE: Android Studio - androids offical android IDE supported by Jetbrains and Google.
  2. Language : Java - The famous java programming language first developed by James Gosling and his team in 1990s.
  3. Emulator : Nox Player - An emulator fast enough for my slow machine.

Gradle Scripts

We start by exploring our gradle scripts.

(a). build.gradle(App)

Here is our app level build.gradle file. We have the dependencies DSL where we add our dependencies.

This file is called app level build.gradle since it is located in the app folder of the project.

If you are using Android Studio version 3 and above use implementation keyword while if you are using a version less than 3 then still use the compile keyword.

Once you have modified this build.gradle file you have to sync your project. Android Studio will indeed prompt you to do so.

You must set your minSdkVersion to atleast 16 as that is the minimum our HorizontalPicker supports.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.devosha.horizontalpicker"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testImplementation 'junit:junit:4.12'
    implementation 'com.android.support:appcompat-v7:28.0.0-beta01'
    implementation 'com.android.support:recyclerview-v7:28.0.0-beta01'
    implementation 'com.github.jhonnyx2012:horizontal-picker:1.0.6'
}

Java Code

Android apps can be mainly written in Java or Kotlin. These days however there are many frameworks like Flutter also which use languages like Dart.

In this class we are using Java programming language.

We will have these classes in our project.

(c). MainActivity.kt

This is our MainActivity. Here's the full code of the MainActivity.

  • class MainActivity.
  • This is our launcher activity and will display our Horizontal DateTime Picker.
  • This class will implement the DatePickerListener interface.
package com.devosha.horizontalpicker;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.github.jhonnyx2012.horizontalpicker.DatePickerListener;
import com.github.jhonnyx2012.horizontalpicker.HorizontalPicker;

import org.joda.time.DateTime;

public class MainActivity extends AppCompatActivity implements DatePickerListener {

    /**
     * Function: onCreate()
     *
     * This is our `onCreate()` callback.
     * First we will inflate the `activity_main()` layout and set it as the layout
     * for this activity via the `setContentView()` method.
     * Then we reference our HorizontalPicker via the findViewById() method.
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        HorizontalPicker picker= (HorizontalPicker) findViewById(R.id.datePicker);
        picker.setListener(this)
                .setDays(120)
                .setOffset(7)
                .setDateSelectedColor(Color.DKGRAY)
                .setDateSelectedTextColor(Color.WHITE)
                .setMonthAndYearTextColor(Color.DKGRAY)
                .setTodayButtonTextColor(getResources().getColor(R.color.colorPrimary))
                .setTodayDateTextColor(getResources().getColor(R.color.colorPrimary))
                .setTodayDateBackgroundColor(Color.GRAY)
                .setUnselectedDayTextColor(Color.DKGRAY)
                .setDayOfWeekTextColor(Color.DKGRAY )
                .setUnselectedDayTextColor(getResources().getColor(R.color.primaryTextColor))
                .showTodayButton(false)
                .init();
        picker.setBackgroundColor(Color.LTGRAY);
        picker.setDate(new DateTime());
    }

    @Override
    public void onDateSelected(DateTime dateSelected) {
        Toast.makeText(this, dateSelected.toString(), Toast.LENGTH_SHORT).show();
    }
    //end
}

Layout Resources

(a). activity_main.xml

This is our main activitys layout. It will contain our HorizontalPicker which will be rendering our dates.

This layout will get inflated into the main activitys user interface. This will happen via the Activity's setContentView() method which will require us to pass it the layout.

We will do so inside the onCreate() method of Activity.

We use the following elements:

  1. LinearLayout
  2. HorizontalPicker
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.github.jhonnyx2012.horizontalpicker.HorizontalPicker
        android:id="@+id/datePicker"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post