circular (endless) scroll recyclerview android

Outline of Article Content
1. How to create a circular (endless) scroll RecyclerView
2. This android recyclerview endless scroll example contains list of 6 images with  HORIZONTAL scroll
3. Uses  modulo operator to find next image from list using int positionInList = position % itemList.size();
4. Method getItemCount()  returns Integer.MAX_VALUE; (This makes the recyclerview about to endless)
5. To set the initial position of RecyclerView to the first item of image list using     layoutManagerStoreFilter.scrollToPosition(((Integer.MAX_VALUE/2)-((Integer.MAX_VALUE/2)%list.size())));
6. Used a SnapHelper class to swipe one image at a time.



activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBlack"
    tools:context=".MainActivity">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerViewCircular"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>

</android.support.constraint.ConstraintLayout>

layout_slider_image.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/image_slider"
        android:layout_width="match_parent"
        android:scaleType="fitXY"
        android:src="@drawable/ic_launcher_background"
        android:layout_height="250dp" />
</LinearLayout>

CicularScrollableRecyclerViewAdapter.java
package com.example.espl.circularscrollingrecyclerview;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;

import java.util.ArrayList;
import java.util.List;

public class CicularScrollableRecyclerViewAdapter extends RecyclerView.Adapter<CicularScrollableRecyclerViewAdapter.ViewHolderImage> {

    private List<Integer> itemList =new ArrayList<>();
    private Context mContext;

    public CicularScrollableRecyclerViewAdapter(Context context, /*DefaultImageLoader imageLoader,*/ List<Integer> list2) {
        try {
            this.mContext = context;
            this.itemList = list2;
//            Log.e("listSizeup::","::"+ itemList.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public ViewHolderImage onCreateViewHolder(ViewGroup viewGroup, int i) {
        View itemViewFooterMenu = LayoutInflater.from(viewGroup.getContext()).inflate(
                R.layout.layout_slider_image, viewGroup, false);
        return new ViewHolderImage(itemViewFooterMenu);
    }

    Integer getItem(int position){
        return itemList.get(position);
    }

    @Override
    public void onBindViewHolder(ViewHolderImage viewHolder, int position) {
        Log.e("ViewHOlderCalled","::"+position);
        RequestOptions requestOptions=new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL)
                .error(R.drawable.ic_launcher_background)
                .placeholder(R.drawable.ic_launcher_background);

        int positionInList = position % itemList.size();

        Glide.with(mContext)
                .load(mContext.getResources().getDrawable(itemList.get(positionInList)))
                .apply(requestOptions)
                .into(viewHolder.image_slider);
    }

    public int getItemCount() {
        return Integer.MAX_VALUE;
    }

    class  ViewHolderImage extends RecyclerView.ViewHolder{
        ImageView image_slider;
        public ViewHolderImage(@NonNull View itemView) {
            super(itemView);
            image_slider=itemView.findViewById(R.id.image_slider);
        }
    }
}

MainActivity.java
package com.example.espl.circularscrollingrecyclerview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerViewCircular;
    private List<Integer> list=new ArrayList<>();
    CicularScrollableRecyclerViewAdapter cicularScrollableRecyclerViewAdapter;
    LinearLayoutManager layoutManagerStoreFilter;

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

        layoutManagerStoreFilter= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        recyclerViewCircular.setLayoutManager(layoutManagerStoreFilter);

        list.add(R.drawable.image1);
        list.add(R.drawable.image2);
        list.add(R.drawable.image3);
        list.add(R.drawable.image4);
        list.add(R.drawable.image5);
        list.add(R.drawable.image6);

        cicularScrollableRecyclerViewAdapter=new CicularScrollableRecyclerViewAdapter(this,list);

        SnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(recyclerViewCircular);

        recyclerViewCircular.setAdapter(cicularScrollableRecyclerViewAdapter);

        layoutManagerStoreFilter.scrollToPosition(((Integer.MAX_VALUE/2)-((Integer.MAX_VALUE/2)%list.size())));
    }
}

build.gradle (Project)
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
 
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath 'com.google.gms:google-services:4.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle (app)
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.espl.circularscrollingrecyclerview"
        minSdkVersion 15
        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'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:28.0.0'
    //glide
    implementation 'com.google.firebase:firebase-dynamic-links:16.0.1'
    implementation 'com.google.firebase:firebase-appindexing:16.0.1'

    implementation 'com.github.bumptech.glide:glide:4.8.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
    implementation 'com.google.firebase:firebase-core:16.0.1'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
apply plugin: 'com.google.gms.google-services'

No comments:

Post a Comment

Popular Posts