自定义View

一个很规范的自定义View实例:

1)继承View
public class CircleView extends View{

        private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

        private int mColor = Color.RED;

        public CircleView(Context context){

        super(context);

        init();

}

        public CircleView(Context context,AttributeSet attrs){

                this(context,attrs,0);

        }

        public CircleView(Context context,AttributeSet attrs,int defStyleAttr){

                super(context,attrs,defStyleAttr);

                TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.CircleView);

                mColor=a.getColor(R.styleable.CircleView_circle_color,Color.RED);

                a.recycle();

                init();

        }

        private void init(){

                mPaint.setColor(mColor);

        }

        @Override

        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){

                super.onMeasure(widthMeasureSpec,heightMeasureSpec);

                int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);

                int heightSpeceMode = MeasureSpec.getMode(heightMeasureSpec);

                int widthSpceSize = MeasureSpec.getSize(widthMeasureSpec);

                int heightSpceSize = MeasureSpec.getSize(heightMeasureSpec);

                if(widthSpecMode == MeasureSpec.AT_MOST && heightSpeceMode ==                                           MeasureSpec.AT_MOST){

                        setMeasuredDimension(200,200);

                }else if(widthSpecMode == MeasureSpec.AT_MOST){

                         setMeasuredDimension(200,heightSpceSize);

                }else if(heightSpeceMode == MeasureSpec.AT_MOST){

                        setMeasuredDimension(widthSpceSize,200);

                }

        }

        @Override

        protected void onDraw(Canvas canvas){

                super.onDraw(canvas);

                final int paddingLeft = getPaddingLeft();

                final int paddingTop = getPaddingTop();

                final int paddintRight = getPaddingRight();

                final int paddingBottom = getPaddingBottom();

                int width = getWidth()- paddingLeft - paddintRight;

                int height = getHeight() - paddingLeft - paddintRight;

                int radius = Math.min(width,height) / 2;

                canvas.drawCircle(paddingLeft + width / 2,paddingTop + height / 2,radius,mPaint);

        }

}

2)继承ViewGroup

public class HorizontalScrollViewEx extends ViewGroup{

        private static final String TAG = "HorizontalScrollViewEx";

        private int mChildrenSize;

        private int mChildWidth;

        private int mChildIndex;

        //分别记录上次滑动的坐标

        private int mLastX = 0;

        private int mLastY = 0;

        //分别记录上次滑动的坐标(onInterceptTouchEvent)

        private int mLastXIntecept = 0;

        private int mLastYIntecept = 0;

        private Scroller mScroller;

        private VelocityTracker mVelocityTracker;

        public HorizontalScrollViewEx(Context context){

                super(context);

                init();

        }

        public HorizontalScrollViewEx(Context context,AttributeSet attrs){

                super(context,attrs);

                init();

        }

        public HorizontalScrollViewEx(Context context,AttributeSet attrs,int defStyleAttr){

                super(context,attrs,defStyleAttr);

                init();

        }

        private void init(){

                if(mScroller == null){

                mScroller = new Scroller(getContext());

                mVelocityTracker = VelocityTracker.obtain();

        }

}

        @Override

        public boolean onInterceptTouchEvent(MotionEvent event){

                boolean intercepted = false;

                int x =(int) event.getX();

                int y =(int) event.getY();

                switch(event.getAction()){

                case MotionEvent.ACTION_DOWN:{

                        intercepted = false;

                        if(!mScroller.isFinished()){

                        mScroller.abortAnimation();

                        intercepted=true;

                        }

                        break;

                }

                case MotionEvent.ACTION_MOVE:{

                        int deltaX = x - mLastXIntecept;

                        int deltaY = y - mLastYIntecept;

                        if(Math.abs(deltaX)>Math.abs(deltaY)){

                        intercepted = true;

                        }else{

                        intercepted = false;

                        }

                        break;

                 }

                case MotionEvent.ACTION_UP:{

                        intercepted = false;

                        break;

                        }

                        default:

                        break;

                        }

                        mLastX = x;

                        mLastY = y;

                        mLastXIntecept = x;

                        mLastYIntecept = y;

                        return intercepted;

                }

        @Override

        public boolean onTouchEvent(MotionEvent event){

                        mVelocityTracker.addMovement(event);

                        int x = (int) event.getX();

                        int y = (int) event.getY();

                        switch (event.getAction()){

                        case MotionEvent.ACTION_DOWN:{

                        if(!mScroller.isFinished()){

                                mScroller.abortAnimation();

                        }

                        break;

                        }

                        case MotionEvent.ACTION_MOVE:{

                                int deltaX = x - mLastX;

                                int deltaY = y - mLastY;

                                scrollBy(-deltaX,0);

                                break;

                        }

                        case MotionEvent.ACTION_UP:{

                                int scrollX = getScrollX();

                                mVelocityTracker.computeCurrentVelocity(1000);

                                float xVelocity = mVelocityTracker.getXVelocity();

                                if(Math.abs(xVelocity) >=50){

                                                mChildIndex = xVelocity > 0 ? mChildIndex-1 : mChildIndex + 1;

                                }else{

                                                mChildIndex = (scrollX + mChildWidth/2)/mChildWidth;

                                }

                                                mChildIndex = Math.max(0,Math.min(mChildIndex,mChildrenSize -1));

                                                int dx = mChildIndex * mChildWidth -scrollX;

                                                smoothScrollBy(dx ,0);

                                                mVelocityTracker.clear();

                                                break;

                                }

                        default:

                                                break;

                                }

                                                mLastX = x;

                                                mLastY = y;

                                                return true;

                                }

        @Override

        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){

                        super.onMeasure(widthMeasureSpec,heightMeasureSpec);

                        int measuredWidth = 0;

                        int measureHeight = 0;

                        final int childCount = getChildCount();

                        measureChildren(widthMeasureSpec,heightMeasureSpec);

                        int widthSpaceSize = MeasureSpec.getSize(widthMeasureSpec);

                        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);

                        int heightSpceSize = MeasureSpec.getSize(heightMeasureSpec);

                        int heightSpeceMode = MeasureSpec.getMode(heightMeasureSpec);

                        if(childCount == 0){

                                                setMeasuredDimension(0,0);

                        }else if(widthSpecMode == MeasureSpec.AT_MOST && heightSpeceMode ==                         MeasureSpec.AT_MOST){

                                                final View childView = getChildAt(0);

                                                measuredWidth = childView.getMeasuredWidth() * childCount;

                                                measureHeight = childView.getMeasureHeight();

                                                setMeasuredDimension(measuredWidth,measureHeight);

                        }else if(heightSpeceMode == MeasureSpec.AT_MOST){

                                                final View childView = getChildAt(0);

                                                measureHeight =childView.getMeasureHeight();

                                                setMeasuredDimension(widthSpaceSize,measureHeight);

                        }else if(widthSpecMode == MeasureSpec.AT_MOST){

                                                final View childView = getChildAt(0);

                                                measuredWidth = childView.getMeasuredWidth() * childCount;

                                                setMeasuredDimension(measuredWidth,heightSpceSize);

                        }

                        }

        @Override

        protected void onLayout(boolean changed,int l,int t, int r,int b){

                        int childLeft = 0;

                        final int childCount = getChildCount();

                        mChildrenSize = childCount;

                        for(int i=0;i<childCount;i++){

                        final View childView = getChildAt(i);

                        if(childView.getVisibility() != View.GONE){

                        final int childWidth = childView.getMeasuredWidth();

                        mChildWidth = childWidth;

                        childView.layout(childLeft,0,childLeft + childWidth,childView.getMeasureHeight());

                        childLeft += childWidth;

                        }

                        }

                        }

        private void smoothScrollBy(int dx,int dy){

                        mScroller.startScroll(getScrollX(),0,dx,0,500);

                        invalidate();

    }

        @Override

        public void computeScroll(){

                        if(mScroller.computeScrollOffset()){

                                                scrollTo(mScroller.getCurrX(),mScroller.getCurrY());

                                                postInvalidate();

                        }

        }

        @Override

        protected void onDetachedFromWindow(){

                        mVelocityTracker.recycle();

                        super.onDetachedFromWindow();

        }

}

                

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 198,030评论 5 464
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,198评论 2 375
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 144,995评论 0 327
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,973评论 1 268
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,869评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,766评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,967评论 3 388
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,599评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,886评论 1 293
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,901评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,728评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,504评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,967评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,128评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,445评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,018评论 2 343
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,224评论 2 339

推荐阅读更多精彩内容