用android补间动画写一个悬浮球动画效果
时间: 2023-10-05 10:06:39 浏览: 72
好的,以下是一个简单的悬浮球动画效果的实现方法:
1. 在布局文件中添加一个 ImageView 作为悬浮球,并设置其初始位置和大小。
```xml
<ImageView
android:id="@+id/floating_ball"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:src="@drawable/floating_ball"
android:layout_gravity="top|start" />
```
2. 在代码中定义两个动画:一个是悬浮球向上移动的动画,一个是悬浮球向下移动的动画。
```java
// 向上移动的动画
Animation upAnimation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0f,
Animation.RELATIVE_TO_SELF, 0f,
Animation.RELATIVE_TO_SELF, 0f,
Animation.RELATIVE_TO_SELF, -1f);
upAnimation.setDuration(500);
// 向下移动的动画
Animation downAnimation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0f,
Animation.RELATIVE_TO_SELF, 0f,
Animation.RELATIVE_TO_SELF, -1f,
Animation.RELATIVE_TO_SELF, 0f);
downAnimation.setDuration(500);
```
3. 在悬浮球上添加点击事件,当点击时播放向上移动的动画;再次点击时播放向下移动的动画。
```java
ImageView floatingBall = findViewById(R.id.floating_ball);
floatingBall.setOnClickListener(new View.OnClickListener() {
boolean isUp = false;
@Override
public void onClick(View v) {
if (isUp) {
v.startAnimation(downAnimation);
isUp = false;
} else {
v.startAnimation(upAnimation);
isUp = true;
}
}
});
```
这样就完成了一个简单的悬浮球动画效果。当用户点击悬浮球时,它会向上移动一段距离;再次点击时,它会向下移动回到原来的位置。你可以根据实际需求修改动画的属性,比如移动距离、动画时长等。