Garmaine Staff asked 1 year ago

I am creating a simple gallery in Kotlin. I am implementing an XML fading effect, so each time the Next or Back button is clicked, the image will fade in for 3 seconds. On the first image it fades in for only half of that time. The next images still have a fade, but only of about .5 seconds. It isn't the XML file because I tested it on another project and it works fine. I believe it has something to do with how I'm integrating it with the loops. You can see I placed the code for the animation in both click listeners. I just started learning both languages two weeks ago, so any advice would help. Thank you.

package com.example.gallery

import android.app.ActionBar.LayoutParams
import android.app.Activity
import android.os.Bundle
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.Button
import android.widget.FrameLayout
import android.widget.ImageSwitcher
import android.widget.ImageView
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : Activity() {
    private var iS: ImageSwitcher? = null
    private var btn1: Button? = null
    private var btn2: Button? = null
    val myGallery = intArrayOf(R.drawable.beach_house,R.drawable.cars,R.drawable.moss, 
 R.drawable.pier, R.drawable.tree)
    var i = 0

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

        btn1 = findViewById<View>(R.id.button) as Button
        btn2 = findViewById<View>(R.id.button2) as Button
        iS = findViewById<View>(R.id.imageSwitcher) as ImageSwitcher

        iS!!.setFactory {
            val myView = ImageView(applicationContext)
            myView.scaleType = ImageView.ScaleType.FIT_CENTER
            myView.layoutParams = FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT)
            myView
        }

        btn1!!.setOnClickListener {
            val animFadeIn =
                AnimationUtils.loadAnimation(applicationContext, android.R.anim.fade_in)
            iS!!.startAnimation(animFadeIn)

                if (i == myGallery.size) {
                    i = 0
                    imageSwitcher.setImageResource(myGallery[i])
                    i++

                } else{
                    imageSwitcher.setImageResource(myGallery[i])
                    i++
                }
        }

        btn2!!.setOnClickListener {

            val animFadeIn =
                AnimationUtils.loadAnimation(applicationContext, android.R.anim.fade_in)
            iS!!.startAnimation(animFadeIn)

            if (i == myGallery.size) {
                i = 0
                imageSwitcher.setImageResource(myGallery[i])
                i++

            } else{
                imageSwitcher.setImageResource(myGallery[i])
                i++
            }
        }
    }
}