我正在为Android编写一个提示器应用程序,我正在尝试让脚本以可定义的速率自动滚动。我试图通过扩展Scrollview并编写新的SmoothScrollBy函数来实现。这是我的代码。
自定义ScrollView:
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;
}
});
我做错了吗?当我点击一下。没有任何事情发生。
感谢。