我正在向我的HorizontalScrollView
添加浮动箭头,这会让用户知道当前视图之外还有更多项目。
我需要的是如何判断View是否已滚动到最大值。你会想到方法getMaxScrollAmount()
会给你这个 - 它没有,在我的代码中它给了我视图的宽度。去了解为什么。这是我的代码 - 简单明了:
final ImageView leftArrow = (ImageView) toReturn.findViewById(R.id.leftArrow);
final ImageView rightArrow = (ImageView) toReturn.findViewById(R.id.rightArrow);
final HorizontalScrollView scrollView = (HorizontalScrollView) toReturn.findViewById(R.id.actionBarHoriztonalScroll);
final GestureDetector gd = new GestureDetector(new SimpleOnGestureListener() {
@Override
public boolean onScroll(MotionEvent e1,
MotionEvent e2,
float distanceX,
float distanceY) {
if(scrollView.getScrollX() == 0) {
leftArrow.setVisibility(View.GONE);
} else {
leftArrow.setVisibility(View.VISIBLE);
}
if(scrollView.getScrollX() == scrollView.getMaxScrollAmount() ||
scrollView.getMaxScrollAmount() == 0) {
rightArrow.setVisibility(View.GONE);
} else {
rightArrow.setVisibility(View.VISIBLE);
}
Log.v(ClientDetailsFragment.class.getSimpleName(), "max: " + scrollView.getMaxScrollAmount() +
"current: " + scrollView.getScrollX());
return super.onScroll(e1, e2, distanceX, distanceY);
}
});
scrollView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent ev) {
gd.onTouchEvent(ev);
return false;
}
});
以上调试输出:
10-03 14:36:16.343: VERBOSE/(20508): max: 240 current: 126
10-03 14:36:16.363: VERBOSE/(20508): max: 240 current: 127
10-03 14:36:16.386: VERBOSE/(20508): max: 240 current: 132
10-03 14:36:16.398: VERBOSE/(20508): max: 240 current: 143
10-03 14:36:16.417: VERBOSE/(20508): max: 240 current: 149
10-03 14:36:16.433: VERBOSE/(20508): max: 240 current: 152
10-03 14:36:16.449: VERBOSE/(20508): max: 240 current: 152
10-03 14:36:16.468: VERBOSE/(20508): max: 240 current: 152
(在这种情况下,152是Max)
答案 0 :(得分:21)
水平滚动视图的子级应具有正确的宽度。试试这个
Log.e("ScrollWidth",Integer.toString(horizontalScrollview.getChildAt(0).getMeasuredWidth()-
getWindowManager().getDefaultDisplay().getWidth()));
这应该是最大滚动量。
将以下代码放入onCreate方法
ViewTreeObserver vto = scrollView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
scrollView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
Log.e("ScrollWidth",Integer.toString(horizontalScrollview.getChildAt(0)
.getMeasuredWidth()-getWindowManager().getDefaultDisplay().getWidth()));
}
});