The library is a RecyclerView-based implementation of a scrollable list, where current item is centered and can be changed using swipes. It is similar to a ViewPager, but you can quickly and painlessly create layout, where views adjacent to the currently selected view are partially or fully visible on the screen.

 

Android Discretescrollview
Android Discretescrollview

 

Gradle

Add this into your dependencies block.

compile 'com.yarolegovich:discrete-scrollview:1.1.4'

Download soucr code

 

Please see the sample app for examples of library usage.

 

GifSampleWeather

How to use Android Discretescrollview

General

The library uses a custom LayoutManager to adjust items’ positions on the screen and handle scroll, however it is not exposed to the client code. All public API is accessible through DiscreteScrollView class, which is a simple descendant of RecyclerView.

If you have ever used RecyclerView – you already know how to use this library. One thing to note – you should NOT set LayoutManager.

Usage:

  1. Add DiscreteScrollView to your layout either using xml or code:
  2. Create your implementation of RecyclerView.Adapter. Refer to the sample for an example, if you don’t know how to do it.
  3. Set the adapter.
  4. You are done!
<com.yarolegovich.discretescrollview.DiscreteScrollView
  android:id="@+id/picker"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  app:dsv_orientation="horizontal|vertical" />

 

DiscreteScrollView scrollView = findViewById(R.id.picker);
scrollView.setAdapter(new YourAdapterImplementation());

 

API

Layout

scrollView.setOrientation(Orientation o); //Sets an orientation of the view
scrollView.setOffscreenItems(count); //Reserve extra space equal to (childSize * count) on each side of the view

 

Related to the current item:

scrollView.getCurrentItem(); //returns adapter position of the currently selected item or -1 if adapter is empty.
scrollView.scrollToPosition(int position); //position becomes selected
scrollView.smoothScrollToPosition(int position); //position becomes selected with animated scroll
scrollView.setItemTransitionTimeMillis(int millis); //determines how much time it takes to change the item on fling, settle or smoothScroll

 

Transformations

One useful feature of ViewPager is page transformations. It allows you, for example, to create carousel effect. DiscreteScrollView also supports page transformations.

scrollView.setItemTransformer(transformer);

public interface DiscreteScrollItemTransformer {
    /**
     * In this method you apply any transform you can imagine (perfomance is not guaranteed).
     * @param position is a value inside the interval [-1f..1f]. In idle state:
     * |view1|  |currentlySelectedView|  |view2|
     * -view1 and everything to the left is on position -1;
     * -currentlySelectedView is on position 0;
     * -view2 and everything to the right is on position 1.
     */
    void transformItem(View item, float position); 
}

 

Because scale transformation is the most common, I included a helper class – ScaleTransformer, here is how to use it:

cityPicker.setItemTransformer(new ScaleTransformer.Builder()
  .setMaxScale(1.05f) 
  .setMinScale(0.8f) 
  .setPivotX(Pivot.X.CENTER) // CENTER is a default one
  .setPivotY(Pivot.Y.BOTTOM) // CENTER is a default one
  .build());

 

You may see how it works on GIFs.

Callbacks

  • Scroll state changes:
  • Scroll:
  • scrollView.setScrollStateChangeListener(listener);
    
    public interface ScrollStateChangeListener<T extends ViewHolder> {
    
      void onScrollStart(T currentItemHolder, int adapterPosition); //called when scroll is started, including programatically initiated scroll
      
      void onScrollEnd(T currentItemHolder, int adapterPosition); //called when scroll ends
      /**
       * Called when scroll is in progress. 
       * @param scrollPosition is a value inside the interval [-1f..1f], it corresponds to the position of currentlySelectedView.
       * In idle state:
       * |view1|  |currentlySelectedView|  |view2|
       * -view1 is on position -1;
       * -currentlySelectedView is on position 0;
       * -view2 is on position 1.
       * @param currentHolder - ViewHolder of a current view
       * @param newCurrent - ViewHolder of a view that moved closer to the center
       */
      void onScroll(float scrollPosition, @NonNull T currentHolder, @NonNull T newCurrentHolder); 
    }

     

  • Scroll:
  • scrollView.setScrollListener(listener);
    
    public interface ScrollListener<T extends ViewHolder> {
      //The same as ScrollStateChangeListener, but for the cases when you are interested only in onScroll()
      void onScroll(float scrollPosition, @NonNull T currentHolder, @NonNull T newCurrentHolder);
    }

     

  • Current selection changes:
  • scrollView.setOnItemChangedListener(listener);
    
    public interface OnItemChangedListener<T extends ViewHolder> {
      /**
       * Called when new item is selected. It is similar to the onScrollEnd of ScrollStateChangeListener, except that it is 
       * also called when currently selected item appears on the screen for the first time.
       */
      void onCurrentItemChanged(@NonNull T viewHolder, int adapterPosition); 
    }

     

  • Ex code
public class DiscreteScrollViewOptions {

    private static DiscreteScrollViewOptions instance;

    private final String KEY_TRANSITION_TIME;

    public static void init(Context context) {
        instance = new DiscreteScrollViewOptions(context);
    }

    private DiscreteScrollViewOptions(Context context) {
        KEY_TRANSITION_TIME = context.getString(R.string.pref_key_transition_time);
    }

    public static void configureTransitionTime(DiscreteScrollView scrollView) {
        final BottomSheetDialog bsd = new BottomSheetDialog(scrollView.getContext());
        final TransitionTimeChangeListener timeChangeListener = new TransitionTimeChangeListener(scrollView);
        bsd.setContentView(R.layout.dialog_transition_time);
        defaultPrefs().registerOnSharedPreferenceChangeListener(timeChangeListener);
        bsd.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                defaultPrefs().unregisterOnSharedPreferenceChangeListener(timeChangeListener);
            }
        });
        bsd.findViewById(R.id.dialog_btn_dismiss).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bsd.dismiss();
            }
        });
        bsd.show();
    }

    public static void smoothScrollToUserSelectedPosition(final DiscreteScrollView scrollView, View anchor) {
        PopupMenu popupMenu = new PopupMenu(scrollView.getContext(), anchor);
        Menu menu = popupMenu.getMenu();
        for (int i = 0; i < scrollView.getAdapter().getItemCount(); i++) {
            menu.add(String.valueOf(i + 1));
        }
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int destination = Integer.parseInt(String.valueOf(item.getTitle())) - 1;
                scrollView.smoothScrollToPosition(destination);
                return true;
            }
        });
        popupMenu.show();
    }

    public static int getTransitionTime() {
        return defaultPrefs().getInt(instance.KEY_TRANSITION_TIME, 150);
    }

    private static SharedPreferences defaultPrefs() {
        return PreferenceManager.getDefaultSharedPreferences(App.getInstance());
    }

    private static class TransitionTimeChangeListener implements SharedPreferences.OnSharedPreferenceChangeListener {

        private WeakReference<DiscreteScrollView> scrollView;

        public TransitionTimeChangeListener(DiscreteScrollView scrollView) {
            this.scrollView = new WeakReference<>(scrollView);
        }

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            if (key.equals(instance.KEY_TRANSITION_TIME)) {
                DiscreteScrollView scrollView = this.scrollView.get();
                if (scrollView != null) {
                    scrollView.setItemTransitionTimeMillis(sharedPreferences.getInt(key, 150));
                } else {
                    sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
                }
            }
        }
    }
}

 

By Ponglang Petrung

Administrator and PJ at Kamibit Thailand, Android Developer at CodeGears Co., Ltd. and Android Developer, and iOS Application Developer at Appdever

Share your thoughts

Leave a Reply

Loading Facebook Comments ...
Loading Disqus Comments ...