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;
}
}
ScrollerLayout
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 1、 python高级编程1.1面向对象进阶1.1.1元类1.1.2python是动态语言1.1.3__slots...