我需要自动制作HorizontalScrollView卷轴。
自动,我的意思是:
我已经尝试了以下实施,但似乎没有完全发挥作用。 (视图从L滚动到R,但无法从R滚动到L)
Timer timer = new Timer("horizontalScrollViewTimer");
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (horizontalScrollView.canScrollHorizontally(View.FOCUS_RIGHT)) {
horizontalScrollView.smoothScrollBy(5, 0);
} else {
while (horizontalScrollView.canScrollHorizontally(View.FOCUS_LEFT)) {
horizontalScrollView.smoothScrollBy(-5, 0);
if (!horizontalScrollView.canScrollHorizontally(View.FOCUS_LEFT)) {
break;
}
}
}
}
});
}
}, 3000, 50);
任何帮助将不胜感激。 TIA。
答案 0 :(得分:0)
@ soumyadip001的答案对我不起作用,因为scrollingLeft从来都不是真的,但是我的这种解决方案对我有用。使用此解决方案,您可以实现无限循环。
int scrollAmount =0; //compute scrolling amount
boolean scrollingLeft = false;
//get the view at the rightmost part of the horizontalscrollview
View viewRight = horizontalScrollView.getChildAt(horizontalScrollView.getChildCount() - 1);
Timer timer = new Timer("horizontalScrollViewTimer");
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (!scrollingLeft) {
horizontalScrollView.smoothScrollBy(5, 0);
scrollAmount+= 5; //increment scroll amount
if (scrollAmount >= viewRight.getRight()) { //check
scrollingLeft = true;
}
}
else {
if (scrollingLeft ) {
horizontalScrollView.smoothScrollBy(-5, 0);
scrollAmount-=5;
if(scrollAmount<=0) {
scrollingLeft = false;
scrollAmount =0;
}
}
}
}
});
}
}, 3000, 50);
注意:取消定时器onPause以避免内存泄漏或崩溃
onPause(){
if(timer!=null)
timer.cancel();
}