public class ScrollerLayout extends ViewGroup {
private Scroller mScroller;
private int currentDisplayPosition = 0;
public ScrollerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mScroller = new Scroller(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
measureChild(childView, widthMeasureSpec, heightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (changed) {
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
int childMeasuredWidth = childView.getMeasuredWidth();
childView.layout(
i * childMeasuredWidth,
0,
(i + 1) * childMeasuredWidth,
childView.getMeasuredHeight());
}
}
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
invalidate();
}
}
/**
* 滚动至指定位置
*/
public void smoothScrollToPosition(int position){
int childCount = getChildCount();
if (position > childCount || position < 0) {
return;
}
currentDisplayPosition = position;
int dx = position * getWidth() - getScrollX();
mScroller.startScroll(getScrollX(), 0, dx, 0);
invalidate();
}
/**
* 滚动至下一个
*/
public void smoothScrollToPrevious(){
smoothScrollToPosition(--currentDisplayPosition);
}
/**
* 滚动至上一个
*/
public void smoothScrollToNext(){
smoothScrollToPosition(++currentDisplayPosition);
}
/**
* @return 当前显示位置
*/
public int getCurrentPosition(){
return currentDisplayPosition;
}
}
网友评论