android 自定义View学习总结-继承自ViewGroup

来源:互联网 发布:淘宝授权书怎么找哇 编辑:程序博客网 时间:2024/05/16 15:49

一、android 自定义View学习总结-继承自ViewGroup

android中自定义view可以有继承view,继承viewgroup,继承系统的View(如LinearLayout,FrameLayout,TextView等)。

public class MyView extends ViewGroup{    public MyView(Context context, AttributeSet attrs) {}     @Override    protected void onLayout(boolean changed, int l, int t, int r, int b) {    }}

继承自ViewGroup需要实现它的onLayout方法,因为这个方法是抽象方法。

onLayout(boolean changed, int l, int t, int r, int b)

onLayout有五个参数,l,t是代表一个view左上角的点,r,b是代表右下角的点。

二、例子

1、创建一个自定义View

public class MyView extends ViewGroup {    private GestureDetector gestureDetector;    public MyView(Context context, AttributeSet attrs) {        super(context, attrs);        gestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){            @Override            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {                scrollBy((int)distanceX,getScrollY());                return true;            }        });    }    @Override    protected void onLayout(boolean changed, int l, int t, int r, int b) {        for(int i=0;i<this.getChildCount();i++){            View childView = getChildAt(i);            childView.layout(i*getWidth(),0,(i+1)*getWidth(),getHeight());        }    }    @Override    public boolean onTouchEvent(MotionEvent event) {        gestureDetector.onTouchEvent(event);        super.onTouchEvent(event);        return true;    }}

从上面创建自定义View的onLayout中可以看出,将会给自定义View的子View从左到右全屏分布。同时,使用GestureDetector 进行滑动手势的响应操作,利用scrollBy进行拖动。

2、给自定义View添加子View

        for(int i=0;i<3;i++){            ImageView imageView = new ImageView(this);            imageView.setBackgroundResource(R.mipmap.ic_launcher);            mMyView.addView(imageView);        }

3、效果图

这里写图片描述

这里写图片描述

利用这个原理,可以实现导航页功能。

0 0