Use these examples to learn how to implement a CarouselView in Android via Kotlin.

Example 1: carousel-view

Useful library for showing list in sliding mode or carousel mode

Options

  • showing horizontal and vertical
  • auto scrolling (with pause/resume)
  • change listener scrolling
  • slider mode/ carousel mode
  • change scrolling speed

This example will comprise the following files:

  • EmptySampleModel.kt
  • MainActivity.kt
  • SampleAdapter.kt
  • SampleModel.kt

Step 1: Create Project

  1. Open your AndroidStudio IDE.
  2. Go to File-->New-->Project to create a new project.

Step 2: Add Dependencies

Add to rootbuild.gradle:

    maven { url "https://jitpack.io" }

Add to module build.gradle:

    implementation 'com.github.alirezat775:carousel-view:{latest-version}'

Step 3: Design Layouts

*(a). activity_main.xml

Create a file named activity_main.xml and design it as follows:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        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"
        tools:context=".sample.MainActivity">

    <alirezat775.lib.carouselview.CarouselView
            android:id="@+id/carousel_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

*(b). item_carousel.xml

Create a file named item_carousel.xml and design it as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="250dp"
              android:layout_height="250dp">

    <TextView
            android:layout_margin="12dp"
            android:textColor="@android:color/white"
            android:background="@color/colorPrimary"
            android:gravity="center"
            android:textSize="22sp"
            android:id="@+id/item_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</LinearLayout>

*(c). item_empty_carousel.xml

Create a file named item_empty_carousel.xml and design it as follows:

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

    <TextView
            android:layout_margin="12dp"
            android:textColor="@android:color/white"
            android:background="@color/colorAccent"
            android:gravity="center"
            android:textSize="22sp"
            android:id="@+id/item_empty_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</LinearLayout>

Step 4: Write Code

Write Code as follows:

*(a). EmptySampleModel.kt

Create a file named EmptySampleModel.kt

Here is the full code

package alirezat775.carouselview.sample

import alirezat775.lib.carouselview.CarouselModel

class EmptySampleModel constructor(private val text: String) : CarouselModel() {

    fun getText(): String {
        return text
    }
}

*(b). MainActivity.kt

Create a file named MainActivity.kt

Here is the full code

package alirezat775.carouselview.sample

import alirezat775.carouselview.R
import alirezat775.lib.carouselview.Carousel
import alirezat775.lib.carouselview.CarouselLazyLoadListener
import alirezat775.lib.carouselview.CarouselListener
import alirezat775.lib.carouselview.CarouselView
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private var hasNextPage: Boolean = true
    val TAG: String = this::class.java.name

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val adapter = SampleAdapter()
        val carousel = Carousel(this, carousel_view, adapter)
        carousel.setOrientation(CarouselView.HORIZONTAL, false)
        carousel.autoScroll(true, 5000, true)
        carousel.scaleView(true)
        carousel.lazyLoad(true, object : CarouselLazyLoadListener {
            override fun onLoadMore(page: Int, totalItemsCount: Int, view: CarouselView) {
                if (hasNextPage) {
                    Log.d(TAG, "load new item on lazy mode")
                    carousel.add(SampleModel(11))
                    carousel.add(SampleModel(12))
                    carousel.add(SampleModel(13))
                    carousel.add(SampleModel(14))
                    carousel.add(SampleModel(15))
                    hasNextPage = false
                }
            }
        })
        adapter.setOnClickListener(object :
            SampleAdapter.OnClick {
            override fun click(model: SampleModel) {
                carousel.remove(model)
            }
        })
//        carousel.scrollSpeed(100f)
//        carousel.enableSlider(true)

        carousel.addCarouselListener(object : CarouselListener {
            override fun onPositionChange(position: Int) {
                Log.d(TAG, "currentPosition : $position")
            }

            override fun onScroll(dx: Int, dy: Int) {
                Log.d(TAG, "onScroll dx : $dx -- dy : $dx")
            }
        })

//        carousel.add(EmptySampleModel("empty list"))
        carousel.add(SampleModel(1))
        carousel.add(SampleModel(2))
        carousel.add(SampleModel(3))
        carousel.add(SampleModel(4))
        carousel.add(SampleModel(5))
        carousel.add(SampleModel(6))
        carousel.add(SampleModel(7))
        carousel.add(SampleModel(8))
        carousel.add(SampleModel(9))
        carousel.add(SampleModel(10))

    }
}

*(c). SampleAdapter.kt

Create a file named SampleAdapter.kt

Here is the full code

package alirezat775.carouselview.sample

import alirezat775.carouselview.R
import alirezat775.lib.carouselview.CarouselAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import kotlinx.android.synthetic.main.item_carousel.view.*
import kotlinx.android.synthetic.main.item_empty_carousel.view.*

/**
 * Author:  Alireza Tizfahm Fard
 * Date:    2019-06-14
 * Email:   [email protected]
 */

class SampleAdapter : CarouselAdapter() {

    private val EMPTY_ITEM = 0
    private val NORMAL_ITEM = 1

    private var vh: CarouselViewHolder? = null
    var onClick: OnClick? = null

    fun setOnClickListener(onClick: OnClick?) {
        this.onClick = onClick
    }

    override fun getItemViewType(position: Int): Int {
        return when (getItems()[position]) {
            is EmptySampleModel -> EMPTY_ITEM
            else -> NORMAL_ITEM
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CarouselViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return if (viewType == NORMAL_ITEM) {
            val v = inflater.inflate(R.layout.item_carousel, parent, false)
            vh = MyViewHolder(v)
            vh as MyViewHolder
        } else {
            val v = inflater.inflate(R.layout.item_empty_carousel, parent, false)
            vh = EmptyMyViewHolder(v)
            vh as EmptyMyViewHolder
        }
    }

    override fun onBindViewHolder(holder: CarouselViewHolder, position: Int) {
        when (holder) {
            is MyViewHolder -> {
                vh = holder
                val model = getItems()[position] as SampleModel
                (vh as MyViewHolder).title.text = model.getId().toString()
            }
            else -> {
                vh = holder
                val model = getItems()[position] as EmptySampleModel
                (vh as EmptyMyViewHolder).titleEmpty.text = model.getText()
            }
        }
    }

    inner class MyViewHolder(itemView: View) : CarouselViewHolder(itemView) {

        var title: TextView = itemView.item_text

        init {
            title.setOnClickListener { onClick?.click(getItems()[adapterPosition] as SampleModel) }
        }

    }

    inner class EmptyMyViewHolder(itemView: View) : CarouselViewHolder(itemView) {
        var titleEmpty: TextView = itemView.item_empty_text
    }

    interface OnClick {
        fun click(model: SampleModel)
    }
}

*(d). SampleModel.kt

Create a file named SampleModel.kt

Here is the full code

package alirezat775.carouselview.sample

import alirezat775.lib.carouselview.CarouselModel

class SampleModel constructor(private var id: Int) : CarouselModel() {

    fun getId(): Int {
        return id
    }
}

Run

Simply copy the source code into your Android Project,Build and Run.

Reference

Download code here.
Follow code author here.

Example 2: CarouselView

An android carousel library for RecyclerView

Here are demp exampels:

alt text
alt text

Step 1: Install it

Current Version:

Add the following

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}
dependencies {
    implementation 'com.github.jama5262:CarouselView:1.2.2'
}

Step 2: Add to Layout

Below is all the XML attributes that the CarouselView has

<com.jama.carouselview.CarouselView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:enableSnapping="true"
    app:scaleOnScroll="false"
    app:setAutoPlay="true"
    app:setAutoPlayDelay="3000"
    app:carouselOffset="center"
    app:indicatorAnimationType="drop"
    app:indicatorRadius="5"
    app:indicatorPadding="5"
    app:indicatorSelectedColor="@color/colorAccent"
    app:indicatorUnselectedColor="@color/colorPrimary"
    app:size="10"
    app:spacing="10"
    app:resource="@layout/image_carousel_item"/>

Kotlin Implementation

class CarouselActivity : AppCompatActivity() {

    private val images = arrayListOf(R.drawable.boardwalk_by_the_ocean, 
            R.drawable.journal_and_coffee_at_table, R.drawable.tying_down_tent_fly)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_carousel)

        val carouselView = findViewById<CarouselView>(R.id.carouselView)

        carouselView.apply {
            size = images.size
            resource = R.layout.carousel_item
            autoPlay = true
            indicatorAnimationType = IndicatorAnimationType.THIN_WORM
            carouselOffset = OffsetType.CENTER
            setCarouselViewListener { view, position ->
                // Example here is setting up a full image carousel
                val imageView = view.findViewById<ImageView>(R.id.imageView)
                imageView.setImageDrawable(resources.getDrawable(images[position]))
            }
            // After you finish setting up, show the CarouselView
            show()
        }
    }
}

Java Implementation

class CenteredCarouselActivity extends AppCompatActivity {

  private int[] images = {R.drawable.boardwalk_by_the_ocean,
      R.drawable.journal_and_coffee_at_table, R.drawable.tying_down_tent_fly};

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

    CarouselView carouselView = findViewById(R.id.carouselView);

    carouselView.setSize(images.length);
    carouselView.setResource(R.layout.center_carousel_item);
    carouselView.setAutoPlay(true);
    carouselView.setIndicatorAnimationType(IndicatorAnimationType.THIN_WORM);
    carouselView.setCarouselOffset(OffsetType.CENTER);
    carouselView.setCarouselViewListener(new CarouselViewListener() {
      @Override
      public void onBindView(View view, int position) {
        // Example here is setting up a full image carousel
        ImageView imageView = view.findViewById(R.id.imageView);
        imageView.setImageDrawable(getResources().getDrawable(images[position]));
      }
    });
    // After you finish setting up, show the CarouselView
    carouselView.show();
  }
}

Full Example

This example will comprise the following files:

  • CenteredCarouselActivity.kt
  • ImageCarouselActivity.kt
  • StartCarouselActivity.kt
  • MainActivity.java

Step 1: Create Project

  1. Open your AndroidStudio IDE.
  2. Go to File-->New-->Project to create a new project.

Step 2: Add Dependencies

As has been described above.

Step 3: Design Layouts

*(a). activity_centered_carousel.xml

Create a file named activity_centered_carousel.xml and design it as follows:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    tools:context=".examples.CenteredCarouselActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:fontFamily="serif"
        android:lineSpacingExtra="8sp"
        android:text="With the improvments of tablets and digital magazines are becoming visually enticing and readable magazines with its graphic arts"
        android:textColor="@android:color/background_dark"
        android:textSize="18sp"
        app:layout_constraintEnd_toStartOf="@+id/guideline2"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toBottomOf="@+id/textView3" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:fontFamily="serif"
        android:text="Magazines"
        android:textColor="@android:color/background_dark"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toStartOf="@+id/guideline2"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:fontFamily="serif"
        android:lineSpacingExtra="8sp"
        android:text="At the same time digitizing  platforms are broadening  the scope of where digial magazines can be published, such as within websites and on, smartphones"
        android:textColor="@android:color/background_dark"
        android:textSize="18sp"
        app:layout_constraintEnd_toStartOf="@+id/guideline2"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="20dp" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="385dp" />

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView">

        <com.jama.carouselview.CarouselView
            android:id="@+id/carouselView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:spacing="20" />
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

*(b). activity_image_carousel.xml

Create a file named activity_image_carousel.xml and design it as follows:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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="#D84315"
    tools:context=".examples.ImageCarouselActivity">

    <TextView
        android:id="@+id/textViewCount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:fontFamily="monospace"
        android:text="2/3"
        android:textColor="#212121"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="@+id/floatingActionButtonRight"
        app:layout_constraintEnd_toStartOf="@+id/floatingActionButtonRight"
        app:layout_constraintStart_toEndOf="@+id/floatingActionButtonLeft"
        app:layout_constraintTop_toBottomOf="@+id/carouselView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text='"'
        android:textAllCaps="false"
        android:textColor="#212121"
        android:textSize="50dp"
        android:textStyle="bold"
        app:layout_constraintStart_toStartOf="@+id/guideline3"
        app:layout_constraintTop_toBottomOf="@+id/textViewCount" />

    <TextView
        android:id="@+id/textViewDesc"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:fontFamily="monospace"
        android:text="TextView"
        android:textColor="@android:color/background_light"
        android:textSize="40sp"
        app:layout_constraintEnd_toStartOf="@+id/guideline4"
        app:layout_constraintStart_toStartOf="@+id/guideline3"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        tools:text="@tools:sample/lorem" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="379dp" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="32dp" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floatingActionButtonLeft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:clickable="true"
        android:focusable="true"
        app:backgroundTint="#212121"
        app:fabSize="mini"
        app:layout_constraintStart_toStartOf="@+id/guideline3"
        app:layout_constraintTop_toBottomOf="@+id/carouselView"
        app:srcCompat="@drawable/ic_arrow_back_black_24dp" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floatingActionButtonRight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:clickable="true"
        android:focusable="true"
        app:backgroundTint="#212121"
        app:fabSize="mini"
        app:layout_constraintEnd_toStartOf="@+id/guideline4"
        app:layout_constraintTop_toBottomOf="@+id/carouselView"
        app:srcCompat="@drawable/ic_arrow_forward_black_24dp" />

    <com.jama.carouselview.CarouselView
        android:id="@+id/carouselView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

*(c). activity_main.xml

Create a file named activity_main.xml and design it as follows:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    tools:context="com.jama.carouselviewexample.MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

*(d). activity_start_carousel.xml

Create a file named activity_start_carousel.xml and design it as follows:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    tools:context=".examples.StartCarouselActivity">

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline6"
        app:layout_constraintTop_toBottomOf="@+id/textView5">

        <com.jama.carouselview.CarouselView
            android:id="@+id/carouselView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline6"
        app:layout_constraintTop_toBottomOf="@+id/textView6">

        <com.jama.carouselview.CarouselView
            android:id="@+id/carouselView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <TextView
        android:id="@+id/textView5"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif-condensed-medium"
        android:text="Movies"
        android:textColor="#263238"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline6"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView6"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif-condensed-medium"
        android:text="Trending"
        android:textColor="#263238"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline6"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout2" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="20dp" />
</androidx.constraintlayout.widget.ConstraintLayout>

*(e). center_carousel_item.xml

Create a file named center_carousel_item.xml and design it as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <androidx.cardview.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:cardCornerRadius="7dp"
        app:cardElevation="10dp">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="200dp"
            android:layout_height="250dp"
            android:scaleType="centerCrop"
            tools:srcCompat="@tools:sample/avatars[3]" />
    </androidx.cardview.widget.CardView>
</LinearLayout>

*(f). examples_items.xml

Create a file named examples_items.xml and design it as follows:

<?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:orientation="vertical"
    android:paddingLeft="20dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp">

    <TextView
        android:id="@+id/textViewExamples"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textColor="@android:color/background_dark"
        android:textSize="24sp" />
</LinearLayout>

*(g). image_carousel_item.xml

Create a file named image_carousel_item.xml and design it as follows:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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="wrap_content"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="350dp"
        android:scaleType="centerCrop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/avatars[3]" />

    <TextView
        android:id="@+id/textViewTitle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:fontFamily="monospace"
        android:text="TextView"
        android:textColor="@android:color/background_light"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="@+id/imageView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline5"
        app:layout_constraintTop_toTopOf="@+id/imageView"
        app:layout_constraintVertical_bias="0.86" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="33dp" />
</androidx.constraintlayout.widget.ConstraintLayout>

*(h). start_carousel_movies_item.xml

Create a file named start_carousel_movies_item.xml and design it as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="200dp"
    android:layout_height="wrap_content"
    android:background="@android:color/background_light"
    android:orientation="vertical">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:cardCornerRadius="15dp"
        app:cardElevation="10dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="200dp"
                android:layout_height="270dp"
                android:scaleType="centerCrop"
                tools:srcCompat="@tools:sample/avatars[3]" />

        </LinearLayout>
    </androidx.cardview.widget.CardView>

    <TextView
        android:id="@+id/textViewTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="5dp"
        android:fontFamily="sans-serif-medium"
        android:text="Title"
        android:textColor="#263238"
        android:textSize="18sp"
        android:textStyle="bold" />

    <RatingBar
        android:id="@+id/ratingBar"
        style="?android:attr/ratingBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:isIndicator="true"
        android:numStars="5"
        android:rating="4"
        android:stepSize="0.1" />

</LinearLayout>

*(i). start_carousel_trending_item.xml

Create a file named start_carousel_trending_item.xml and design it as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="100dp"
    android:layout_height="wrap_content"
    android:background="@android:color/background_light"
    android:orientation="vertical">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:cardCornerRadius="15dp"
        app:cardElevation="10dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="100dp"
                android:layout_height="140dp"
                android:scaleType="centerCrop"
                tools:srcCompat="@tools:sample/avatars[3]" />

        </LinearLayout>
    </androidx.cardview.widget.CardView>

    <TextView
        android:id="@+id/textViewTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="5dp"
        android:fontFamily="sans-serif-medium"
        android:text="Title"
        android:textColor="#263238"
        android:textSize="18sp"
        android:textStyle="bold" />

    <RatingBar
        android:id="@+id/ratingBar"
        style="?android:attr/ratingBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:isIndicator="true"
        android:numStars="5"
        android:rating="4" />

</LinearLayout>

Step 4: Write Code

Write Code as follows:

*(a). CenteredCarouselActivity.kt

Create a file named CenteredCarouselActivity.kt

Here is the full code

package com.jama.carouselviewexample.examples

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import com.jama.carouselview.enums.IndicatorAnimationType
import com.jama.carouselview.enums.OffsetType
import com.jama.carouselviewexample.R
import kotlinx.android.synthetic.main.activity_centered_carousel.*

class CenteredCarouselActivity : AppCompatActivity() {

    val images = arrayListOf(R.drawable.boardwalk_by_the_ocean, R.drawable.journal_and_coffee_at_table, R.drawable.tying_down_tent_fly)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_centered_carousel)

        carouselView.apply {
            size = images.size
            autoPlay = true
            autoPlayDelay = 3000
            resource = R.layout.center_carousel_item
            indicatorAnimationType = IndicatorAnimationType.THIN_WORM
            carouselOffset = OffsetType.CENTER
            setCarouselViewListener { view, position ->
                val imageView = view.findViewById<ImageView>(R.id.imageView)
                imageView.setImageDrawable(resources.getDrawable(images[position]))
            }
            show()
        }
    }
}

*(b). ImageCarouselActivity.kt

Create a file named ImageCarouselActivity.kt

Here is the full code

package com.jama.carouselviewexample.examples

import android.graphics.drawable.Drawable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.jama.carouselview.CarouselScrollListener
import com.jama.carouselviewexample.R
import kotlinx.android.synthetic.main.activity_image_carousel.*

class ImageCarouselActivity : AppCompatActivity() {

    val images = arrayListOf(R.drawable.boardwalk_by_the_ocean, R.drawable.journal_and_coffee_at_table, R.drawable.tying_down_tent_fly)
    private val imageTitle = arrayListOf("Cape Town, South Africa", "New York, USA", "Iceland")
    val imageDesc = arrayListOf("Broad walk by the ocean", "Journal and coffee at table", "Tying down tent fly")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_image_carousel)

        textViewCount.text = "1/${images.size}"
        textViewDesc.text = imageDesc[0]

        val scrollListener = object : CarouselScrollListener {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int, position: Int) {
                textViewCount.text = "${position + 1}/${images.size}"
                textViewDesc.text = imageDesc[position]
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {}
        }

        carouselView.apply {
            size = images.size
            resource = R.layout.image_carousel_item
            hideIndicator(true)
            setCarouselViewListener { view, position ->
                val imageView = view.findViewById<ImageView>(R.id.imageView)
                imageView.setImageDrawable(resources.getDrawable(images[position]))
                val textView = view.findViewById<TextView>(R.id.textViewTitle)
                textView.text = imageTitle[position]
            }
            carouselScrollListener = scrollListener
            show()
        }

        floatingActionButtonLeft.setOnClickListener {
            carouselView.currentItem -= 1
        }

        floatingActionButtonRight.setOnClickListener {
            carouselView.currentItem += 1
        }

    }
}

*(c). StartCarouselActivity.kt

Create a file named StartCarouselActivity.kt

Here is the full code

package com.jama.carouselviewexample.examples

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import com.jama.carouselviewexample.R
import kotlinx.android.synthetic.main.activity_start_carousel.*

class StartCarouselActivity : AppCompatActivity() {

    private val movies = arrayListOf(R.drawable.harry_potter, R.drawable.konosuba, R.drawable.i_am_legend, R.drawable.priates)
    private val moviesTitles = arrayListOf("Harry Potter", "Konosuba", "I Am Legend", "Pirates of the Caribbean")
    private val trending = arrayListOf(R.drawable.lord_of_ring, R.drawable.naruto, R.drawable.spirited, R.drawable.mad_max)

    private val trendingTitles = arrayListOf("Lord of the Rings", "The Last Naruto the Movie", "Spirited Away", "Mad Max")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_start_carousel)

        carouselView1.apply {
            size = movies.size
            resource = R.layout.start_carousel_movies_item
            scaleOnScroll = true
            spacing = 50
            hideIndicator(true)
            setCarouselViewListener { view, position ->
                val imageView = view.findViewById<ImageView>(R.id.imageView)
                imageView.setImageDrawable(resources.getDrawable(movies[position]))
                val textView = view.findViewById<TextView>(R.id.textViewTitle)
                textView.text = moviesTitles[position]
            }
            show()
        }

        carouselView2.apply {
            val trendingMovies = trending + movies
            val trendingTitle = trendingTitles + moviesTitles

            size = trendingMovies.size
            resource = R.layout.start_carousel_trending_item
            spacing = 50
            hideIndicator(true)
            setCarouselViewListener { view, position ->
                val imageView = view.findViewById<ImageView>(R.id.imageView)
                imageView.setImageDrawable(resources.getDrawable(trendingMovies[position]))
                val textView = view.findViewById<TextView>(R.id.textViewTitle)
                textView.text = trendingTitle[position]
            }
            show()
        }

    }
}

*(d). MainActivity.java

Create a file named MainActivity.java

Here is the full code

package com.jama.carouselviewexample;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jama.carouselviewexample.examples.CenteredCarouselActivity;
import com.jama.carouselviewexample.examples.ImageCarouselActivity;
import com.jama.carouselviewexample.examples.StartCarouselActivity;

public class MainActivity extends AppCompatActivity {

  RecyclerView recyclerView;
  private RecyclerView.Adapter mAdapter;
  private RecyclerView.LayoutManager layoutManager;

  private String[] examples = {"Image Carousel Example", "Centered Carousel Example", "Start Carousel Example"};

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

    recyclerView = findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    mAdapter = new Adapter(examples);
    recyclerView.setAdapter(mAdapter);

  }

  class Adapter extends RecyclerView.Adapter<Adapter.AdapterViewHolder> {

    private String[] mDataset;

    Adapter(String[] mDataset) {
      this.mDataset = mDataset;
    }

    @NonNull
    @Override
    public AdapterViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
      View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.examples_items, parent, false);
      return new AdapterViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull AdapterViewHolder holder, final int position) {
      TextView textView = holder.itemView.findViewById(R.id.textViewExamples);
      textView.setText(mDataset[position]);
      textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          if (position == 0) {
            startActivity(new Intent(MainActivity.this, ImageCarouselActivity.class));
          } else if (position == 1) {
            startActivity(new Intent(MainActivity.this, CenteredCarouselActivity.class));
          } else if (position == 2) {
            startActivity(new Intent(MainActivity.this, StartCarouselActivity.class));
          }
        }
      });
    }

    @Override
    public int getItemCount() {
      return mDataset.length;
    }

    class AdapterViewHolder extends RecyclerView.ViewHolder {
      AdapterViewHolder(@NonNull View itemView) {
        super(itemView);
      }
    }
  }
}

Run

Simply copy the source code into your Android Project,Build and Run.

Reference

Download code here.
Follow code author here.

Categorized in: