Android连续点赞特效
时间: 2023-12-23 07:28:09 浏览: 144
Android点赞特效
5星 · 资源好评率100%
Android连续点赞特效可以通过自定义View来实现。下面是一个简单的示例代码:
```java
public class LikeView extends View {
private static final int DEFAULT_TEXT_SIZE = 30;
private static final int DEFAULT_TEXT_COLOR = Color.RED;
private static final int DEFAULT_ANIMATION_DURATION = 1000;
private String mText;
private int mTextSize;
private int mTextColor;
private int mAnimationDuration;
private Paint mPaint;
private ValueAnimator mAnimator;
public LikeView(Context context) {
this(context, null);
}
public LikeView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
private void init(AttributeSet attrs) {
// 从xml属性中获取自定义属性值
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.LikeView);
mText = typedArray.getString(R.styleable.LikeView_likeText);
mTextSize = typedArray.getDimensionPixelSize(R.styleable.LikeView_likeTextSize, DEFAULT_TEXT_SIZE);
mTextColor = typedArray.getColor(R.styleable.LikeView_likeTextColor, DEFAULT_TEXT_COLOR);
mAnimationDuration = typedArray.getInt(R.styleable.LikeView_likeAnimationDuration, DEFAULT_ANIMATION_DURATION);
typedArray.recycle();
// 初始化画笔
mPaint = new Paint();
mPaint.setTextSize(mTextSize);
mPaint.setColor(mTextColor);
// 初始化动画
mAnimator = ValueAnimator.ofFloat(0, 1);
mAnimator.setDuration(mAnimationDuration);
mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
invalidate();
}
});
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mText != null) {
// 根据动画进度绘制文本
float progress = (float) mAnimator.getAnimatedValue();
int alpha = (int) (255 * (1 - progress));
mPaint.setAlpha(alpha);
canvas.drawText(mText, 0, mTextSize, mPaint);
}
}
public void startAnimation() {
if (!mAnimator.isRunning()) {
mAnimator.start();
}
}
public void setText(String text) {
mText = text;
invalidate();
}
}
```
使用方法:
1. 在xml布局文件中添加LikeView:
```xml
<com.example.LikeView
android:id="@+id/likeView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:likeText="Like"
app:likeTextSize="30sp"
app:likeTextColor="#FF0000"
app:likeAnimationDuration="1000" />
```
2. 在代码中获取LikeView实例,并调用startAnimation方法开始动画:
```java
LikeView likeView = findViewById(R.id.likeView);
likeView.startAnimation();
```
阅读全文