我有一个ListView,一次只能显示4个项目。我必须逐个滚动一个项目。
用户滚动ListView后,我必须重新调整滚动条以适合4项。我的意思是,我不能将项目显示一半。
另一个问题,是否有任何方法可以获取当前ListView的scrollY偏移量?因为listView.getScrollY()方法来自View,而不是ListView中的Scroller对象。
答案 0 :(得分:3)
我找到了一个很好的解决方案。它对我来说很完美。 可能是我的回答会帮助别人。
class ScrollListener implements AbsListView.OnScrollListener{
boolean aligned;
@Override
public void onScrollStateChanged(AbsListView absListView, int state) {
if (state == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
aligned = false;
}
if (state == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
if (!aligned) {
if (Math.abs(absListView.getChildAt(0).getY()) < Math.abs(absListView.getChildAt(1).getY())) {
listView.smoothScrollToPosition(absListView.getFirstVisiblePosition());
} else {
listView.smoothScrollToPosition(absListView.getLastVisiblePosition());
}
}
aligned = true;
}
}
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
}
我必须说,在我的情况下,我有两个可见的项目,所以如果你有4个,你应该使用索引("getChildAt(0)" and "getChildAt(1)")
。
祝你好运!
答案 1 :(得分:0)
您可以在ScrollView上实现传感器“OnTouchListener”。 然后该技术不会滚动,直到该人至少没有scrooler项目的高度。 代码示例:
scroll.setOnTouchListener(new OnTouchListener()
{
private int mLastY;
public boolean onTouch(View v, MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN: //the user places his finger on the screen
mLastY=(int)event.getY(); //to get the "y" position starting
break;
case MotionEvent.ACTION_MOVE:
if(mLastY-event.getY() >= theSizeOfItem) //if a movement of the size of an item occurs
{
scroll.scrollTo(0, scroll.getScrollY()+ theSizeOfItem));
scroll.invalidate();
mLastY=(int)event.getY(); //reset the starting position to the current position
}
if(event.getY()-mLastY >= theSizeOfItem) //if a movement of the size of an item occurs
{
scroll.scrollTo(0, scroll.getScrollY() - theSizeOfItem));
scroll.invalidate();
mLastY=(int)event.getY(); //reset the starting position to the current position
}
break;
default:
break;
}
return v.onTouchEvent (event); //to use other sensors (OnClick, OnLongClick, ...)
}});
然后必须实现滚动到达结尾的情况!对不起我的英文,我希望它能帮到你