Android Animate Horizontal Scrolling Tiled Background (Kotlin)

Apr 21, 2018

Create a tiling background (@drawable/bg_bitmap_logo_dark) with bitmap and android:tileMode="repeat".

NOTE: it is not possible to use vector image for tiling background as android:src is a required field and cannot be vector image. You might want to refer to this.

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:tileMode="repeat"
    android:src="@drawable/ic_logo_background_dark_tile18_bitmap"
    />

The following is based on code shared by Xaver Kapeller.

Create 2 ImageView.

<FrameLayout
        android:id="@+id/frameLayout2"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:background="@android:color/black"
        >

        <ImageView
            android:id="@+id/background1ImageView"
            app:srcCompat="@drawable/bg_bitmap_logo_dark"
            android:scaleType="fitXY"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <ImageView
            android:id="@+id/background2ImageView"
            app:srcCompat="@drawable/bg_bitmap_logo_dark"
            android:scaleType="fitXY"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />

</FrameLayout>
val display = context.getDisplayMetrics()// % 18 because my tile size is 18px// and to avoid partial crop when both image are joined togetherval width = display.widthPixels + display.widthPixels % 18background1ImageView.layoutParams.width = widthbackground2ImageView.layoutParams.width = width// start animationval animator = ValueAnimator.ofFloat(0.0f, 1.0f)animator.repeatCount = ValueAnimator.INFINITEanimator.interpolator = LinearInterpolator()animator.duration = 20000L // this will control speed of scrollinganimator.addUpdateListener { animation ->    val progress = animation.animatedValue as Float    val width = background1ImageView.getWidth()    val translationX = width * progress    background1ImageView.setTranslationX(translationX)    background2ImageView.setTranslationX(translationX - width)}animator.start()

NOTE: I notice there are ocasionally flickering gap between two images, thus I set FrameLayout color as similar to the image color.

NOTE: I prefer to not use an external library for this purpose thus didn't try AndroidScrollingImageView.

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.