An image slider in an Android app is a dynamic UI component. It allows users to browse through a collection of images by swiping left or right. It enhances the user experience by providing a visually appealing way to display multiple images in a compact space. Often used in galleries, product showcases, or introductory screens, an image slider can include additional features. These features might be auto-scrolling, looping, and clickable images. Clickable images can lead to more detailed views or actions. Implementing a custom image slider involves careful design. You must consider user interaction, performance, and responsive layout. This ensures a smooth and engaging experience across various devices.

First Design the Layout Of the Image Slider

ViewPager: Use a ViewPager for the image slider. These components allow users to swipe through images smoothly.

Slider Adapter: We create an adapter to handle all slider images. This adapter shows our images and starts the animation. It slides one image at a time.

Image Container: Within each page or item in the ViewPager, place an ImageView to show each image.

Indicators (Optional): add small dots at the bottom of the screen. Also, add lines to show the current position in the slider.

Image Slider Default Selected Indicators Drawable

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape
            android:innerRadius="0dp"
            android:shape="ring"
            android:thickness="7dp"
            android:useLevel="false">
            <solid android:color="@color/grey" />
        </shape>
    </item>
</layer-list>

Image Slider Selected Items Indicators Drawable

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>

        <shape
            android:innerRadius="0dp"
            android:shape="ring"
            android:thickness="7dp"
            android:useLevel="false">
            <solid android:color="@color/purple_700" />
            <stroke android:width="1dp" android:color="#7BAEAEAE"/>

        </shape>

    </item>
</layer-list>

Image Slider Selector Drawable

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/dot_selected_items" android:state_selected="true"/>
    <item android:drawable="@drawable/dot_default_items" />
</selector>

Image Slider ViewPager & TabLayout XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="1in"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_marginHorizontal="5dp"
    android:layout_marginVertical="10dp"
    app:cardCornerRadius="8dp"
    app:cardElevation="2dp"
    tools:ignore="InOrMmUsage">

<androidx.viewpager.widget.ViewPager
    android:id="@+id/sliderViewPage"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"/>

<com.google.android.material.tabs.TabLayout
    android:id="@+id/sliderTab"
    android:layout_width="wrap_content"
    android:layout_height="4dp"
    android:background="@android:color/transparent"
    app:tabBackground="@drawable/dot_selector"
    app:tabIndicatorHeight="0dp"
    app:tabRippleColor="@null"
    android:layout_gravity="bottom|center"
    android:layout_marginBottom="10dp"/>

</androidx.cardview.widget.CardView>

Image Slider Adapter

public class SliderAdapter extends PagerAdapter {

    private List<String> imageLinkList;
    private Animation animation;

    public SliderAdapter(List<String> imageLinkList) {
        this.imageLinkList = imageLinkList;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        ImageView sliderImage = new ImageView(container.getContext());
        sliderImage.setScaleType(ImageView.ScaleType.CENTER_CROP);


        animation = AnimationUtils.loadAnimation(container.getContext(), android.R.anim.slide_in_left);
        sliderImage.startAnimation(animation);
        Glide.with(container.getContext()).load(imageLinkList.get(position)).into(sliderImage);
        container.addView(sliderImage, 0);
        return  sliderImage;

    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((ImageView) object);
    }

    @Override
    public int getCount() {
        return imageLinkList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }
}

Setup Image Slider Into Home Page

public class HomeActivity extends AppCompatActivity {

    private ViewPager slider_viewpager;
    private TabLayout sliderTabLayout;
    private List<String> sliderImageList = new ArrayList<>();
    private SliderAdapter sliderAdapter;
    private Runnable runnable = null;
    private Handler handler = new Handler();

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash)

        slider_viewpager = findViewById(R.id.sliderViewPage);
        sliderTabLayout = findViewById(R.id.sliderTab);

        sliderImageList.add("https://i.ytimg.com/vi/fiSWKebAZg8/maxresdefault.jpg");
        sliderImageList.add("https://omisell.com/wp-content/uploads/2021/07/Shopee-5.5.jpg");
        sliderImageList.add("https://cdn.hostadvice.com/2023/11/What-Is-a-Flash-Sale-A-Complete-Guide-with-Examples-and-Tips.png");
        sliderImageList.add("https://d2kh7o38xye1vj.cloudfront.net/wp-content/uploads/2021/02/8th-Feb-1024x576.jpg");

        sliderAdapter = new SliderAdapter(sliderImageList);
        slider_viewpager.setAdapter(sliderAdapter);
        sliderTabLayout.setupWithViewPager(slider_viewpager, true);
        startAutoSlide(sliderAdapter.getCount());


    }

    private void startAutoSlide(final int items) {
        int delay = 4000;
        runnable = new Runnable() {
            @Override
            public void run() {
                int pos = slider_viewpager.getCurrentItem();
                pos = pos+1;
                if (pos >= items) pos = 0;
                slider_viewpager.setCurrentItem(pos);
                handler.postDelayed(runnable, delay);
            }
        };
        handler.postDelayed(runnable, delay);
    }
}

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *