帮我写一个Android的View上下移动带动画的代码
以下是一个简单的示例代码,用于在Android中实现View上下移动带动画效果:
import android.animation.ObjectAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.LinearLayout;
public class AnimatedView extends LinearLayout {
private float lastTouchY;
private float initialY;
private ObjectAnimator animator;
public AnimatedView(Context context) {
super(context);
}
public AnimatedView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AnimatedView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastTouchY = event.getRawY();
initialY = getY();
break;
case MotionEvent.ACTION_MOVE:
float currentY = event.getRawY();
float deltaY = currentY - lastTouchY;
setY(getY() + deltaY);
lastTouchY = currentY;
break;
case MotionEvent.ACTION_UP:
float finalY = getY();
float distance = finalY - initialY;
animateView(distance);
break;
}
return true;
}
private void animateView(float distance) {
animator = ObjectAnimator.ofFloat(this, "translationY", distance);
animator.setInterpolator(new AccelerateDecelerateInterpolator());
animator.setDuration(300);
animator.start();
}
}
在xml布局文件中使用这个自定义的AnimatedView:
<com.example.AnimatedView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Add your content here -->
</com.example.AnimatedView>
当用户按下并移动View时,View会跟随手指的移动而移动。当用户释放手指时,View会以动画的方式回到初始位置。你可以根据自己的需求进行修改和定制化
原文地址: https://www.cveoy.top/t/topic/hVcO 著作权归作者所有。请勿转载和采集!