Create Carousel Easily in Android App with CarouselView
Carousel is a component to show the users a slideshow, usually images. In Android, we can easily create this component using an open-source library called CarouselView.
Create a New Project
First, let’s create a new project and add this dependency to the newly created project.
implementation 'com.synnapps:carouselview:0.1.4'
Prepare the Images
Now, we need images for our carousel, so choose your own images or grab the examples from here. Save the images in res > drawable so that we have:
XML Layout
After the dependency added and all the images are ready, now let’s create the layout. I assume you create a new project with Basic Activity template, so open content_main.xml and change it’s content to:
com.synnapps.carouselview.CarouselView
is the View name to show the carousel. It can be written only after adding the dependency above.app:fillColor
is the property name to choose the fill color for the circle to show which image position is shown.app:radius
is the property to choose the circle’s size.app:slideInterval
is the property to choose the time interval before moving the next image.app:strokeColor
is the property to choose the stroke color of the circle.app:strikeWidth
is the property name to choose the width of the circle.
MainActivity
Now, let’s move to Java file. Open MainActivity and change it’s content to:
Inline four we create a new object typed CarouselView
- Inline five we create an array of int to store images id that we added in res > drawable
- Inline fourteen we do findViewById() like always
- Inline fifteen we choose the number of the images using length method of the array of sampleImages
- Inline sixteen we call
setImageListener
which will do the work of running the slideshow based on listener we create inline 28-33
Or, if you want it in Kotlin:
You can also use Picasso to load images from URL (don’t forget to add INTERNET permission and the Gradle dependency):
Run the App
Now, let’s run this app and make sure everything works.
Error java.lang.OutOfMemoryError
When I run my app for the first time I got Error java.lang.OutOfMemoryError. It seems that the images are taking too many memories. So, I search the error and I found that adding these two lines to application tag in AndroidManifest.xml will make the app work:
android:hardwareAccelerated="false"
android:largeHeap="true"
Conclusion
With the help of CarouselView, we can easily add image slideshow in the Android app. So, if you want to know more about the library, visit sayyam/CarouselView in Github or you can also see my code here (the library also have the sample which is better)