scroller类似于view中修改值的工具valueanimotion只不过他是在groupview中使用的
scrollto和scrollby都是移动的goup里面或者view里面的内容。
一个是相对于view移动相应位置一个是相对于自己移动
@Override
protected void onFinishInflate() {
super.onFinishInflate();
WindowManager wm = (WindowManager) getContext()
.getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth();
int height = wm.getDefaultDisplay().getHeight();
int childheight = height / 7;
int childwidth = (width + 200) / 7;
for (int i = 0; i < 7; i++) {
TextView tv = new TextView(getContext());
tv.setText(i + "");
if (i % 2 == 0) {
tv.setBackgroundColor(Color.BLUE);
} else {
tv.setBackgroundColor(Color.RED);
}
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "onClick: "+((TextView) v).getText() );
}
});
tv.setLayoutParams(new ViewGroup.LayoutParams(childwidth, childheight));
addView(tv);
}
//刚开始移动到中点
Log.e(TAG, "onFinishInflate: "+getChildAt(0).getWidth()/2 );
scrollTo(childwidth/2,0);
currentposition=childwidth/2;
}
子控件跟随手指的移动:
case MotionEvent.ACTION_DOWN:
downposition = (int) event.getX();
// scrollTo();
Log.e(TAG, "onTouchEvent: down" + downposition);
break;
case MotionEvent.ACTION_MOVE:
moveposition = (int) event.getX();
Log.e(TAG, "onTouchEvent: move" + moveposition);
position = moveposition - downposition;
//if (position>mTouchSlop) {
// currentposition += position;
// }
scrollTo(currentposition -position, 0);
break;
downposition记录按下的位置。
currentposition记录当前已经scrollto的位置。
在up时将scroll的位置添加到currentposition中.
case MotionEvent.ACTION_UP:
currentposition -= position;
tracker.computeCurrentVelocity(1000);
scroller.fling(currentposition, 0, -((int) tracker.getXVelocity()), 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
invalidate();
break;
然后是关于速度监听的使用:
if (tracker == null) {
tracker = VelocityTracker.obtain();
}
tracker.addMovement(event);
tracker.computeCurrentVelocity(1000);
scroller.fling(currentposition, 0, -((int) tracker.getXVelocity()), 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
invalidate();
手指离开时开始fling
@Override
public void computeScroll() {
if (scroller.computeScrollOffset()){
;
Log.e(TAG, "computeScroll: "+getChildAt(0).getX() );
scrollTo(scroller.getCurrX(),scroller.getCurrY());
invalidate();
}else {
//移动完毕储存当前scroll位置
currentposition=scroller.getCurrX();
}
}
computescroll在canvas画图时会调用到他在其中执行相应的移动,然后重新绘制知道scroller执行完。即
scroller.computeScrollOffset()
为false时。
7个view在fling时效果和70个view滚动一样:
;//当scroll过去时我这里简单写一下重复的方法即让7个view看起来无数个view的方法
int h=scroller.getCurrX()%childwidth;
if(h==0){
Log.e(TAG, "computeScroll: " + getChildAt(0).getX());
for (int i = 0; i < 7; i++) {
TextView tv = (TextView) getChildAt(i);
String a = tv.getText().toString();
int b = Integer.valueOf(a);
b++;
tv.setText(b + "");
}
scrollTo(0,0);
}
scrollTo(h,scroller.getCurrY());
invalidate();