kotlin
1:克隆+号,并且添加到activity上
var but = Button(context)//创建一个button对象
//设置大小,位置,背景全部相同
but.text = "+"//设置文本
but.setBackgroundResource(R.drawable.but_jia)//设置背景色
val srcLocation = IntArray(2)
val destLocation = context.getCartLocation()
item_par_but_jia.getLocationInWindow(srcLocation)//获取当前位置
Log.d("zxhlocation",""+srcLocation[0]+"===="+srcLocation[1])//0为x,1为y
but.x = srcLocation[0].toFloat()//设置横纵坐标
but.y = srcLocation[1].toFloat()
context.addButton(but,item_par_but_jia.width,item_par_but_jia.height)//往activity中添加button
2:执行抛物线动画(水平位移,垂直加速位移)
var parAnimationSet :AnimationSet= getParabolaAnimation(srcLocation,destLocation)
parAnimationSet.duration = 800
but.startAnimation(parAnimationSet)
private fun getParabolaAnimation(srcLocation: IntArray, destLocation: IntArray): AnimationSet {
var parAnimationSet :AnimationSet = AnimationSet(false)
var translateAnimationX = TranslateAnimation(
Animation.ABSOLUTE, 0.0f,
Animation.ABSOLUTE, destLocation[0].toFloat()-srcLocation[0].toFloat(),
Animation.ABSOLUTE, 0.0f,
Animation.ABSOLUTE, 0.0f
)
translateAnimationX.duration = 800
parAnimationSet.addAnimation(translateAnimationX)
var translateAnimationY = TranslateAnimation(
Animation.ABSOLUTE,0.0f,
Animation.ABSOLUTE, 0.0f,
Animation.ABSOLUTE, 0.0f,
Animation.ABSOLUTE, destLocation[1].toFloat() - srcLocation[1].toFloat()
)
translateAnimationY.interpolator = AccelerateInterpolator()
translateAnimationY.duration = 800
parAnimationSet.addAnimation(translateAnimationY)
return parAnimationSet
}
3.动画完成后回收克隆的+号
parAnimationSet.setAnimationListener(object :Animation.AnimationListener{
override fun onAnimationEnd(animation: Animation?) {
val viewParent = but.parent
if(viewParent!=null){//当动画结束后,如果对象不为空,就消除该对象
(viewParent as ViewGroup).removeView(but)
}
}
override fun onAnimationRepeat(animation: Animation?) {
}
override fun onAnimationStart(animation: Animation?) {
}
})
}