可以通过touch 上滑下滑来修改mValue的值
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
public class ScrollWheel extends View {
private static final String TAG = "ScrollWheel";
private static final float MAX_STEP = 8.0f;
private static final float DEFAULT_STEP = 0.2f;
private float mValue;
private float mStep;
private float mLastY;
private float mVelocity;
private float mDirection;
public ScrollWheel(Context context) {
super(context);
mValue = 0;
mStep = DEFAULT_STEP;
mLastY = 0;
mVelocity = 0;
mDirection = 0;
}
public ScrollWheel(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mValue = 0;
mStep = DEFAULT_STEP;
mLastY = 0;
mVelocity = 0;
mDirection = 0;
}
public ScrollWheel(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mValue = 0;
mStep = DEFAULT_STEP;
mLastY = 0;
mVelocity = 0;
mDirection = 0;
}
public ScrollWheel(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
mValue = 0;
mStep = DEFAULT_STEP;
mLastY = 0;
mVelocity = 0;
mDirection = 0;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastY = y;
mVelocity = 0;
break;
case MotionEvent.ACTION_MOVE:
float deltaY = y - mLastY;
mLastY = y;
mVelocity = Math.abs(deltaY) * DEFAULT_STEP;
mStep = Math.min(MAX_STEP, mVelocity);
mDirection = deltaY > 0 ? -1 : 1;
mValue += mStep * mDirection;
Log.d(TAG, "Velocity: " + mVelocity + ", Value: " + mValue);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
startInertiaDeceleration();
break;
}
return true;
}
private void startInertiaDeceleration() {
final float deceleration = 0.5f;
post(new Runnable() {
@Override
public void run() {
mVelocity *= deceleration;
mStep = Math.max(DEFAULT_STEP, Math.min(MAX_STEP, mVelocity));
mValue += mStep * mDirection;
Log.d(TAG, "Inertia Velocity: " + mVelocity + ", Value: " + mValue);
if (Math.abs(mVelocity) > DEFAULT_STEP) {
post(this);
}
}
});
}
}