通过点击屏幕一次,使按钮在可见之前不可点击

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

提问人:Balry 提问时间:11/9/2023 更新时间:11/9/2023 访问量:25

问:

我正在尝试使一个不可见的按钮在可见之前无法点击。 按钮实例化如下:

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

hide util 函数如下:

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

该按钮通过一个 onTouch 事件变得可见,该事件触发一个名为 fade 的 util 函数,该函数使用 View.startAnimation 来显示元素(tapMe 是一个跨越整个屏幕宽度/高度=match_parent 的 ScrollView):

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 函数如下:

@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)
}
Android Kotlin 按钮 OnClickListener OnTouchListener

评论


答:

0赞 Pawan Harariya 11/9/2023 #1

您可以使用提供和侦听器的。AnimatorListenerAdapterObjectAnimatoronAnimationStart()onAnimationEnd()

在 上创建扩展函数。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
            }
        })
    }

用于在视图中淡入淡出。ObjectAnimator

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