gpt4 book ai didi

android - Kotlin-多个动画同时出现和/或互相重复

转载 作者:行者123 更新时间:2023-12-02 13:32:46 28 4
gpt4 key购买 nike

我正在尝试在Android Studio中创建一个游戏应用。概念是:有圆圈掉下来,您需要单击/按下它们以使其消失,然后再触摸屏幕底部的线条。为此,我创建了一个以圆圈为图像的ImageView。我将其显示在顶部,并以缓慢的速度向下移动。当我按它时,它消失了。问题是,第二个圆圈在第一个圆圈之后出现,这很好,但是向下的动画没有开始,并且OnClickListener也不起作用。

这是创建圆的代码:

/*Creation of ball via imageView.
ImageView is created on the current Activity Layout with the circle as image.
ImageView is 200x200 and appears in the middle of the screen (horizontal) on top.
*/
private fun drawBall(){
val imageView = ImageView(this)
imageView.setImageDrawable(getDrawable(R.drawable.ball_1))
imageView.layoutParams = LinearLayout.LayoutParams(200, 200)
imageView.x = (width/2.5).toFloat()
layout.addView(imageView)
moveBall(imageView)
}

这是动画开始的代码和圆圈消失的OnClickListener的代码:
//Animation of ball falling down.
private fun moveBall(imageView: ImageView){
val valueAnimator = ValueAnimator.ofFloat(0f, height*0.68.toFloat() )
valueAnimator.addUpdateListener {
val value = it.animatedValue as Float
imageView.translationY = value
}

valueAnimator.interpolator = LinearInterpolator()
valueAnimator.duration = 2500
valueAnimator.start()

//Shooting the ball and incrementing score
imageView.setOnClickListener(){
imageView.visibility = View.INVISIBLE
var currentScore = textView_score.text.toString().toInt()
currentScore++
textView_score.text = currentScore.toString()
}
}

在这里,您可以找到我要创建多个掉落的圆的实例的代码:
//Multiple instances of the falling ball animation.
private fun startBalls(){
val runnable = Runnable { drawBall() }
runnable.run(){
drawBall()
}

val exec = ScheduledThreadPoolExecutor(1)
val period : Long = 1000
exec.scheduleAtFixedRate(runnable,0, period, TimeUnit.MILLISECONDS)
val delay : Long = 1000
exec.scheduleWithFixedDelay(runnable, 0, delay, TimeUnit.MILLISECONDS)
}

我认为我的主要问题是我试图创建多个圆圈实例。
先感谢您。

最佳答案

moveBall()记录表明,当Runnable启动ScheduledThreadPoolExecutor时,未在UI线程上执行该代码。更具体地说,根本不执行valueAnimator.start()之后的下一行(第一次“触摸” UI元素会在非UI线程中导致异常”),因此,除了第一个OnClickListener之外,没有为所有ImageView设置任何代码。

当将Runnable的相同实例与ScheduledThreadPoolExecutor重用时,由于它也为seems to be a problem,因此您可以使用自定义Runnable类,并使其在UI线程上调用drawBall():

class MyRunnable(val functionToInvoke: () -> Unit): Runnable {
override fun run() {
Handler(Looper.getMainLooper()).post(Runnable {
//this will run on the UI thread
functionToInvoke.invoke()
})
}
}
startBalls()中的用法:
val exec = ScheduledThreadPoolExecutor(1)
val period : Long = 1000
exec.scheduleAtFixedRate(MyRunnable({drawBall()}),0, period, TimeUnit.MILLISECONDS)
val delay : Long = 1000
exec.scheduleWithFixedDelay(MyRunnable({drawBall()}), 0, delay, TimeUnit.MILLISECONDS)

关于android - Kotlin-多个动画同时出现和/或互相重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60343695/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com