要在Android中實現滾動選擇控件的動畫效果,可以使用ValueAnimator和Scroller來實現。以下是一個簡單的示例代碼,演示如何實現滾動選擇控件的動畫效果:
public class ScrollPickerView extends View {
private List<String> mDataList;
private Paint mPaint;
private int mTextSize;
private int mTextColor;
private int mItemHeight;
private int mCurrentIndex;
private int mTargetIndex;
private ValueAnimator mAnimator;
public ScrollPickerView(Context context) {
this(context, null);
}
public ScrollPickerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ScrollPickerView);
mTextSize = a.getDimensionPixelSize(R.styleable.ScrollPickerView_textSize, 16);
mTextColor = a.getColor(R.styleable.ScrollPickerView_textColor, Color.BLACK);
mItemHeight = mTextSize + 20;
a.recycle();
mPaint = new Paint();
mPaint.setTextSize(mTextSize);
mPaint.setColor(mTextColor);
mPaint.setTextAlign(Paint.Align.CENTER);
mDataList = new ArrayList<>();
for (int i = 0; i < 100; i++) {
mDataList.add(String.valueOf(i));
}
mCurrentIndex = 0;
mTargetIndex = 0;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int centerY = getHeight() / 2 + mTextSize / 2;
for (int i = -1; i <= 1; i++) {
int index = mCurrentIndex + i;
if (index >= 0 && index < mDataList.size()) {
canvas.drawText(mDataList.get(index), getWidth() / 2, centerY + i * mItemHeight, mPaint);
}
}
}
public void smoothScrollToIndex(final int index) {
if (index < 0 || index >= mDataList.size()) {
return;
}
mAnimator = ValueAnimator.ofInt(mTargetIndex * mItemHeight, index * mItemHeight);
mAnimator.setDuration(500);
mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int value = (int) animation.getAnimatedValue();
mCurrentIndex = value / mItemHeight;
scrollTo(0, value % mItemHeight);
invalidate();
}
});
mAnimator.start();
mTargetIndex = index;
}
}
在這個示例代碼中,我們自定義了一個ScrollPickerView控件,其中實現了一個smoothScrollToIndex方法,可以實現滾動選擇到指定的索引位置并帶有動畫效果。當調用smoothScrollToIndex方法時,會啟動一個ValueAnimator動畫,根據動畫的進度來改變當前選中的索引位置和滾動條的位置,從而實現滾動選擇控件的動畫效果。