package com.example.along.myproject; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import static android.view.MotionEvent.ACTION_MOVE; /** * Created by long on 2017/4/5. */ public class ImageScrollerView extends ViewGroup { /** * 轮播图的实现 * @param context */ private int childcount; private int width; private int height; private int childWidth; private int childHeight; private int x=0; public ImageScrollerView(Context context) { super(context); } public ImageScrollerView(Context context, AttributeSet attrs) { super(context, attrs); } public ImageScrollerView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } /** * 测量过程 * @param widthMeasureSpec * @param heightMeasureSpec */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); /** * 一个viewGroup的宽度和高度是有childview的宽度和高度决定的 * 1,计算childview的个数 * 2,如果子视图的个数等于0,或者子视图的个数不等于0 */ childcount=getChildCount(); if(0==childcount){ setMeasuredDimension(0,0); }else{ measureChildren(widthMeasureSpec,heightMeasureSpec);//测量子视图的宽度和高度 View view=getChildAt(0); childWidth=view.getMeasuredWidth();//子视图的测量宽度 Log.i("ACTION_UP","childWidth"+childWidth); childHeight=view.getMeasuredHeight();//子视图的测量高度 width=childWidth*childcount; height=childHeight; setMeasuredDimension(width,height); } } /** * 要继承viewgroup,必须实现 * @param changed 布局发生变化的时候changed为true * @param l * @param t * @param r * @param b * 将每一子视图放置好,就等於viewgroup放置好了 */ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { /** * 遍历所有的子视图,便对其进行布局的放置 */ int margLeft=0; if(changed){ for(int i=0;i<childcount;i++){ View view=getChildAt(i); //放置好每一个view view.layout(margLeft,0,childWidth+margLeft,childHeight); margLeft+=childWidth; } } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return true; } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: x=(int)event.getX();//获取击屏幕那一瞬间的横坐标 Log.i("MotionEvent","ACTION_DOWN"+x); break; case ACTION_MOVE: int moveX=(int)event.getX();//获取滑动屏幕那一段时间的横坐标 Log.i("MotionEvent","ACTION_MOVE"+moveX); int distance=moveX-x; scrollBy(-distance,0); x=moveX;//移动之后停止在某一处 break; case MotionEvent.ACTION_UP: int scollerX=getScrollX();//获取手抬起那一瞬间的横坐标 Log.i("ACTION_UP","scollerX"+scollerX); int index=(scollerX+childWidth/2)/childWidth; Log.i("ACTION_UP","index"+index); if(index<0){ index=0; }else if(index>childcount-1){ index=childcount-1; } scrollTo(index*childWidth,0); break; } return true; } }
手动轮番图
最新推荐文章于 2020-11-18 15:55:28 发布