我正在为 Android 编写提词器应用程序,并且我试图让脚本以可定义的速率自动滚动。我试图通过扩展 Scrollview 并编写一个新的 SmoothScrollBy 函数来做到这一点。这是我的代码。
自定义滚动视图:
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewConfiguration;
import android.view.animation.AnimationUtils;
import android.widget.ScrollView;
import android.widget.Scroller;
public class myScrollView extends ScrollView {
static final int ANIMATED_SCROLL_GAP = 250;
private long mLastScroll;
static final float MAX_SCROLL_FACTOR = 0.5f;
private Scroller mScroller;
public myScrollView(Context context) {
super(context);
initScrollView();
}
public myScrollView(Context context, AttributeSet attrs){
super(context,attrs);
initScrollView();
}
public myScrollView(Context context, AttributeSet attrs, int defStyle){
super(context,attrs, defStyle);
initScrollView();
}
private void initScrollView(){
mScroller = new Scroller(getContext());
setFocusable(true);
setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
setWillNotDraw(false);
}
public final void smoothScrollBy(int dx, int dy, int dur) {
if (getChildCount() == 0) {
// Nothing to do.
return;
}
long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
if (duration > ANIMATED_SCROLL_GAP) {
final int height = getHeight() - getPaddingBottom() - getPaddingTop();
final int bottom = getChildAt(0).getHeight();
final int maxY = Math.max(0, bottom - height);
final int scrollY = getScrollY();
dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY;
Log.d("scroll dy", "from" + Integer.toString(getScrollY()) + "to" + Integer.toString(dy));
mScroller.startScroll(getScrollX(), getScrollY(), 0, dy, dur);
invalidate();
} else {
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
Log.d("scroller", "fallback");
scrollBy(dx, dy);
}
mLastScroll = AnimationUtils.currentAnimationTimeMillis();
}
}
调用函数:
((myScrollView)findViewById(R.id.ScrollView01)).setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
long delta = event.getEventTime() - event.getDownTime();
if(event.getAction() == MotionEvent.ACTION_UP && delta < 200){
((myScrollView)v).smoothScrollBy(0, v.getHeight(), 30000);
}
return false;
}
});
难道我做错了什么?当我点击一下。什么都没发生。
谢谢。