RecyclerView as WheelPicker

Case Study :

Working with an E-Commerce application, I was asked to implement a custom date/time picker for delivery time slot as below.

Fig. 1.1 TimeSlot Picker

Being a lazy developer, my first approach was to look for a library that would make my work a lot easier. And after few (actually many) Google searches, I decided to use AigeStudio’s WheelPicker library.

And where things started to go wrong?

  • Our UI slightly changed and we were having different formats of time for API response and App UI (they were very different). So I had to use a more complex Object model for Collection.
  • Since, There were two WheelPickers in the UI and the data in second one was entirely dependent upon that in first one. There were a lot of issues with changing data.

As Solution to first problem, one can simply override the toString() function and return the required date/time format.

But, In second case there were a lot of issues with changing data. The library provides a single setData() method which in most cases didn’t worked well for us. setSelectedItemPosition() wasn’t working either in few cases.

And then I just get to know of SnapHelper in RecyclerView.

SnapHelper

SnapHelper is the utility class that help to implement snapping in RecyclerView. Support library 24.2.0 introduced two helper classes SnapHelper and LinearSnapHelper for handling snapping in RecyclerView.

Fig 1.2 Demo App

Github Project

Making List

activity_main.xml

MainActivity XML Layout

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.LinearLayoutCompat     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical"     tools:context="com.github.angads25.androidwheel.MainActivity">
    <android.support.v7.widget.AppCompatTextView         android:id="@+id/tv_date"         android:layout_width="match_parent"         android:layout_height="?android:attr/listPreferredItemHeightSmall"         android:gravity="center"         android:textSize="18sp"         android:textStyle="bold"         tools:text="@string/app_name"/>
    <android.support.v7.widget.RecyclerView         android:id="@+id/date_picker"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:background="#000000"         android:foreground="@drawable/shape_picker_shade"         tools:listitem="@layout/list_item_date_time"/>
</android.support.v7.widget.LinearLayoutCompat>

 

DateBean.java

Pojo for Date

package com.github.angads25.androidwheel;
/**
 *
 * Created by Angad Singh on 26/11/17.
 *
 */
public class DateBean {
    private String date;
    private long timeStamp;
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public long getTimeStamp() {
        return timeStamp;
    }
    public void setTimeStamp(long timeStamp) {
        this.timeStamp = timeStamp;
    }
}

list_item_date_time.xml

RecyclerView list item

 

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="?android:attr/listPreferredItemHeight"     android:background="#333333">
    <android.support.v7.widget.AppCompatTextView         android:id="@+id/tv_data"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:gravity="center"         android:textSize="16sp"         android:layout_gravity="center_vertical"         android:layout_marginLeft="16dp"         android:layout_marginStart="16dp"         android:layout_marginRight="16dp"         android:layout_marginEnd="16dp"         android:textColor="#FFFFFF"         tools:text="@string/app_name"/>
</FrameLayout>

PickerAdapter.java

Adapter class for RecyclerView

package com.github.angads25.androidwheel;

 

import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

 

/**
*
* Created by Angad Singh on 22/11/17.
*
*/

 

public class PickerAdapter extends RecyclerView.Adapter {
private Context context;
private ArrayList strings;

public PickerAdapter(Context context, ArrayList strings) {
this.context = context;
this.strings = strings;
}

@Override
public PickerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item_date_time, parent, false);
return new PickerViewHolder(view);
}

@Override
public void onBindViewHolder(PickerViewHolder holder, int position) {
holder.tvData.setText(strings.get(position).getDate());
}

@Override
public int getItemCount() {
return strings.size();
}

class PickerViewHolder extends RecyclerView.ViewHolder {
private AppCompatTextView tvData;

PickerViewHolder(View itemView) {
super(itemView);
tvData = itemView.findViewById(R.id.tv_data);
}
}
}

Making RecyclerView Snap Center Item

MainActivity.java

package com.github.angads25.androidwheel;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.widget.AbsListView;
import java.util.ArrayList;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
    private String[] months = {
            "Jan", "Feb", "Mar",
            "Apr", "May", "Jun",
            "Jul", "Aug", "Sep",
            "Oct", "Nov", "Dec"
    };
    private AppCompatTextView dateTv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Maximum visible items in WheelPicker as a time.
        int maxItems = 3;
        // We will adjust height of recyclerView to fit
        // exactly maximum visible items.
        int recyclerViewHeight = 0;
        TypedValue tv = new TypedValue();
        if (getTheme().resolveAttribute(android.R.attr.listPreferredItemHeight, tv, true)) {
            // Calculating recyclerView height from listItemHeight
            // we are using in our recyclerView list item.
            recyclerViewHeight = maxItems * TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
        }
        dateTv = findViewById(R.id.tv_date);
        final RecyclerView dateList = findViewById(R.id.date_picker);
        LinearLayoutCompat.LayoutParams dateParams = (LinearLayoutCompat.LayoutParams) dateList.getLayoutParams();
        dateParams.height = recyclerViewHeight;
        dateList.setLayoutParams(dateParams);
        final ArrayList<DateBean> arrayList = new ArrayList<>();
        // Adding blank field in beginning of list so that
        // first date item is selectable.
        DateBean padding = new DateBean();
        padding.setDate("");
        arrayList.add(padding);
        // Adding 7 consecutive days to date picker.
        Calendar calendar = Calendar.getInstance();
        for(int i = 0; i < 7; i++) {
            DateBean date = new DateBean();
            date.setDate(
                    months[calendar.get(Calendar.MONTH)] + " " +
                    calendar.get(Calendar.DAY_OF_MONTH) + ", " +
                    calendar.get(Calendar.YEAR));
            date.setTimeStamp(calendar.getTimeInMillis());
            arrayList.add(date);
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        // Adding blank field in last so that last item is
        // selectable.
        arrayList.add(padding);
        PickerAdapter adapter = new PickerAdapter(MainActivity.this, arrayList);
        final LinearLayoutManager manager = new LinearLayoutManager(
                MainActivity.this,
                LinearLayoutManager.VERTICAL,
                false);
        final LinearSnapHelper snapHelper = new LinearSnapHelper();
        // Attaching SnapHelper to recyclerView.
        snapHelper.attachToRecyclerView(dateList);
        // Setting layout manager to recyclerView.
        dateList.setLayoutManager(manager);
        //
        dateList.setOnFlingListener(snapHelper);
        // Setting adapter to recyclerView.
        dateList.setAdapter(adapter);
        // Listening to scroll events on RecyclerView.
        dateList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    View centerView = snapHelper.findSnapView(manager);
                    // Getting position of the center/snapped item.
                    int pos = manager.getPosition(centerView);
                    dateTv.setText(arrayList.get(pos).getDate());
                }
            }
        });
    }
}

Wheel Picker In Action:

Fig. 1.3 Wheel Picker

Remarks:

Fig. 1.4 TimeSlot Picker

I personally think that RecyclerView picker is far better than any other pickers. It comes with all the advantages of RecyclerView. We can use customized item types, add animations and even more.


Posted

in

by

Tags:

Recent Post

  • Behind the Scenes: Building a Multi-Agent System to Handle 80% of Support Tickets Autonomously

    Let’s face it—support tickets are the silent killers of productivity. Behind every “Where’s my order?” or “I forgot my password” lies a bloated system of repetitive manual work, overworked agents, and frustrated customers stuck in virtual queues. Now, consider this: what if 80% of those tickets never needed a human in the first place? In […]

  • Agentic AI Explained: Definition, Benefits, Challenges and Use Cases

    Artificial Intelligence (AI) has evolved significantly, transitioning from rule-based systems to more dynamic, learning-based models. Among the latest advancements is Agentic AI, an AI paradigm that enhances autonomy, decision-making, and self-improvement capabilities. Unlike traditional AI, which primarily follows predefined rules or models, Agentic AI exhibits goal-oriented behavior, adapts to complex environments, and makes decisions with […]

  • AI in payment: Key applications, advantages, and regulatory considerations

    The financial landscape is undergoing a profound transformation, driven by the rapid advancements in artificial intelligence (AI). From enhancing security to streamlining transactions, AI is revolutionizing how we make payments, making the process faster, safer, and more seamless. The global AI in payments market is projected to reach an impressive USD 12.7 billion by 2026, […]

  • Generative AI for IT: Integration approaches, use cases, challenges, ROI evaluation and future outlook

    Generative AI is a game-changer in the IT sector, driving significant cost reductions and operational efficiencies. According to a BCG analysis, Generative AI (GenAI) has the potential to deliver up to 10% savings on IT spending—a transformation that is reshaping multiple facets of technology. The impact is especially profound in application development, where nearly 75% […]

  • Generative AI in Manufacturing: Integration approaches, use cases and future outlook

    Generative AI is reshaping manufacturing by providing advanced solutions to longstanding challenges in the industry. With its ability to streamline production, optimize resource allocation, and enhance quality control, GenAI offers manufacturers new levels of operational efficiency and innovation. Unlike traditional automation, which primarily focuses on repetitive tasks, GenAI enables more dynamic and data-driven decision-making processes, […]

  • Generative AI in Healthcare: Integration, use cases, challenges, ROI, and future outlook

    Generative AI (GenAI) is revolutionizing the healthcare industry, enabling enhanced patient care, operational efficiency, and advanced decision-making. From automating administrative workflows to assisting in clinical diagnoses, GenAI is reshaping how healthcare providers, payers, and technology firms deliver services. A Q1 2024 survey of 100 US healthcare leaders revealed that over 70% have already implemented or […]

Click to Copy