Make button unclickable until it is visible by tapping the screen once

33 views Asked by At

I am trying to make an invisible button unclickable until it is visible. Button is instantiated as such:

val button1 = findViewById<Button>(R.id.button1 )
button1.setOnClickListener {
    val intent = Intent(this, ActivityClass::class.java)
    startActivity(intent)
}
hide(button1)

hide util function is as follows:

@RequiresApi(Build.VERSION_CODES.Q)
fun hide(v: View?) {
    v?.setTransitionVisibility(View.INVISIBLE)
}

The button becomes visible via an onTouch event that triggers a util function called fade that uses View.startAnimation to display elements (tapMe is a ScrollView that spans the entire screen width/height=match_parent):

tapMe.setOnTouchListener(object : View.OnTouchListener {
    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_DOWN -> {
                button1.fadeIn(1000)
                tapMe.setTransitionVisibility(View.INVISIBLE)
            }
        }
        return v?.onTouchEvent(event) ?: true
    }
})

fadeIn util function is as follows:

@RequiresApi(Build.VERSION_CODES.Q)
fun View.fadeIn(durationMillis: Long = 250) {
    this.startAnimation(AlphaAnimation(0F, 1F).apply {
        duration = durationMillis
        startOffset = delay
        fillAfter = true
    })
    this.setTransitionVisibility(View.VISIBLE)
}
1

There are 1 answers

0
Pawan Harariya On

You ca use the AnimatorListenerAdapter of ObjectAnimator that provides onAnimationStart() and onAnimationEnd() listeners.

Create an extension function on ObjectAnimator.

private fun ObjectAnimator.disableViewDuringAnimation(view: View) {
        addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationStart(animation: Animator) {
                view.isEnabled = false
            }

            override fun onAnimationEnd(animation: Animator) {
                view.isEnabled = true
            }
        })
    }

Use ObjectAnimator to fade in your view.

fun View.fadeIn(durationMillis: Long = 250) {
        val animator = ObjectAnimator.ofFloat(this, View.ALPHA, 0f, 1f)
        animator.disableViewDuringAnimation(this)
        animator.duration = durationMillis
        animator.start()
    }