Android 自定义ViewGroup(一)

自定义viewgroup,这个东西可以说简单也简单,说复杂也复杂。主要是因为用到所以复习了一下,那就顺便做个笔记。

暂时只讲简单的用法

一.重要方法

(1)onMeasure 设置viewgroup的大小
(2)onLayout 设置如何摆放子View
(3)generateLayoutParams 设置LayoutParams

最重要的是前面两个方法,所以说viewgroup很简单,你只需要知道在onMeasure 和 onLayout中写什么内容就行。

注:这里说的自定义viewgroup是值直接继承ViewGroup,而不是继承各种Layout之类已封装好的ViewGroup。

1.确定自己要做的viewgroup是怎么样的

首先要确认自己要做出怎样的viewgroup,因为onMeasure和onLayout 可以说是关联很小的,他们是配合使用才能出现自己想要的效果,如果不注意细节的话很容易弄错,所以要先确定自己想做出来的viewgroup是怎样的,才开始做。

2.onMeasure

首先要记好自定义onMeasure的流程,他会先调用onMeasure再调用onLayout,而onMeasure会调用多次,这个以后讲。

(1)onMeasure做的事很简单,就是测量ViewGroup的大小,准确来说是根据子View来测量viewgroup的大小。所以在onMeasure方法里面一般会用measureChildren去测量子view的大小。
(2)onMeasure方法中一般要分两种情况去测量,viewgroup在xml中定义时,宽高是不是wrap_content
你想想,如果viewgroup固定宽高或者填充父布局的话,那实际中的宽高肯定是你定义的,但是如果是wrap_content的话,你就需要自己去设置宽高让它包裹所有子View,所以自定义viewgroup的onMeasure中会分两种情况去setMeasuredDimension宽高

2.onLayout

设置完viewgroup的宽高之后,就要去摆放子view。

(1)摆放子View的规则是,设置这个view的左上角的点在viewgroup的位置:
child.layout(left, top, right,bottom);
而根据这个坐标点和宽高,我们就能在viewgroup中正确的摆放子view
(2)需要注意的是如果子view超出了viewgroup所onMeasure(设置好大小)的部分,那部分不会显示出来。
(3)获取子view的方法View child = getChildAt(i); 得到的view一般是addview时添加view的顺序,但是还有特殊情况,这个过后再解释。

3.generateLayoutParams

设置LayoutParams,那么LayoutParams是什么东西,一般我们给viewgroup添加view都会用到LayoutParams。
翻译过来就是布局参数,通俗点说就是能获取到布局一些特定的属性,比如说布局的边距什么的。反正你正着想,在创建view时LayoutParams设置的属性,在自定义Viewgroup中都能拿到。

这个类系统有很多子类,包括如果你牛逼的话你可以依照谷歌的这种做法,可以自定义LayoutParams,所以具体情况再说。

二.demo

逼逼了这么多,还是应该拿个例子来说,比如说流式布局
流式布局可以用自定义viewgroup来实现,虽然它也可以用recyclerview来实现,但是它的性质和RelativeLayout这些布局一样,应该是一个viewgroup。

我就找了网上一个来说啊,因为我懒得写算法。

public class BerFlowLayout extends ViewGroup {

    //存储所有子View
    private List<List<View>> mAllChildViews = new ArrayList<>();
    //每一行的高度
    private List<Integer> mLineHeight = new ArrayList<>();

    public BerFlowLayout(Context context) {
        super(context);
    }

    public BerFlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BerFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //父控件传进来的宽度和高度以及对应的测量模式
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

        //如果当前ViewGroup的宽高为wrap_content的情况
        int width = 0;//自己测量的 宽度
        int height = 0;//自己测量的高度
        //记录每一行的宽度和高度
        int lineWidth = 0;
        int lineHeight = 0;

        //获取子view的个数
        int childCount = getChildCount();
        for(int i = 0;i < childCount; i ++){
            View child = getChildAt(i);
            //测量子View的宽和高
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            //得到LayoutParams
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

            //子View占据的宽度
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            //子View占据的高度
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
            //换行时候
            if(lineWidth + childWidth > sizeWidth){
                //对比得到最大的宽度
                width = Math.max(width, lineWidth);
                //重置lineWidth
                lineWidth = childWidth;
                //记录行高
                height += lineHeight;
                lineHeight = childHeight;
            }else{//不换行情况
                //叠加行宽
                lineWidth += childWidth;
                //得到最大行高
                lineHeight = Math.max(lineHeight, childHeight);
            }
            //处理最后一个子View的情况
            if(i == childCount -1){
                width = Math.max(width, lineWidth);
                height += lineHeight;
            }
        }
        //wrap_content
        setMeasuredDimension(modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width,
                modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        mAllChildViews.clear();
        mLineHeight.clear();
        //获取当前ViewGroup的宽度
        int width = getWidth();

        int lineWidth = 0;
        int lineHeight = 0;
        //记录当前行的view
        List<View> lineViews = new ArrayList<View>();
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();

            //如果需要换行
            if (childWidth + lineWidth + lp.leftMargin + lp.rightMargin > width) {
                //记录LineHeight
                mLineHeight.add(lineHeight);
                //记录当前行的Views
                mAllChildViews.add(lineViews);
                //重置行的宽高
                lineWidth = 0;
                lineHeight = childHeight + lp.topMargin + lp.bottomMargin;
                //重置view的集合
                lineViews = new ArrayList();
            }
            lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
            lineHeight = Math.max(lineHeight, childHeight + lp.topMargin + lp.bottomMargin);
            lineViews.add(child);
        }
        //处理最后一行
        mLineHeight.add(lineHeight);
        mAllChildViews.add(lineViews);

        //设置子View的位置
        int left = 0;
        int top = 0;
        //获取行数
        int lineCount = mAllChildViews.size();
        for (int i = 0; i < lineCount; i++) {
            //当前行的views和高度
            lineViews = mAllChildViews.get(i);
            lineHeight = mLineHeight.get(i);
            for (int j = 0; j < lineViews.size(); j++) {
                View child = lineViews.get(j);
                //判断是否显示
                if (child.getVisibility() == View.GONE) {
                    continue;
                }
                MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
                int cLeft = left + lp.leftMargin;
                int cTop = top + lp.topMargin;
                int cRight = cLeft + child.getMeasuredWidth();
                int cBottom = cTop + child.getMeasuredHeight();
                //进行子View进行布局
                child.layout(cLeft, cTop, cRight, cBottom);
                left += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            }
            left = 0;
            top += lineHeight;
        }
    }

    /**
     * 与当前ViewGroup对应的LayoutParams
     */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new MarginLayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
    }

    @Override
    protected LayoutParams generateLayoutParams(LayoutParams p) {
        return new MarginLayoutParams(p);
    }

}

1.onMeasure

先看onMeasure,看看它怎么测量整体父布局的。这里循环处理子view,先获取到子view的大小

            //子View占据的宽度
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            //子View占据的高度
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;

然后判断换不换行,如果这个子view的宽度加上前面累计起来的比父布局的宽度宽,那就加一行。

其实这里的onMeasure意图很容易看懂,它的作用就是根据子view来决定高度,所以为什么我之前说要先弄清楚你想做怎么样的效果,比如这里,我想做的效果就是流式布局的效果,那这个布局的高度肯定是根据有多少行来动态决定的吧,而这里的计算就是觉得这个高度的过程。

1.onLayout

这个他这里写得有点麻烦,应该是可以再缩短一些的。

如果累加的宽度+当前子view的宽度+间距 > 一行的宽度,则换行

if (childWidth + lineWidth + lp.leftMargin + lp.rightMargin > width) {
}

换行就设置累计宽度为0: lineWidth = 0;
mAllChildViews就是它存储的第一个装view的二维数组。

然后再对每一行进行操作 for (int i = 0; i < lineCount; i++) {...},然后对left 和top 进行叠加操作。

其实我觉得这里可以在最上面的循环中就直接child.layout对子View进行布局,不用两次循环。他这里的思路是第一次大循环来获取行数并保存二维数组,第二次大循环再设置子view位置。

3.MarginLayoutParams

这里写的

/**
     * 与当前ViewGroup对应的LayoutParams
     */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new MarginLayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
    }

    @Override
    protected LayoutParams generateLayoutParams(LayoutParams p) {
        return new MarginLayoutParams(p);
    }

是为了设置子view和子view间通过margin设置的间距。

4.调用

如果在xml中写子布局,可以直接用,这时设置generateLayoutParams会默认调用3个种的这个方法,你不用去关系LayoutParams。

@Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

但是如果是动态去添加view,你就需要自己去写MarginLayoutParams,那么可以这样写。

                ViewGroup.LayoutParams lp = new ViewGroup.
                        LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                ViewGroup.MarginLayoutParams mlp = new ViewGroup.MarginLayoutParams(lp);
                mlp.setMargins(10,10,10,10);

                textView.setLayoutParams(mlp);

三.总结

最后做个小结吧。你可以看成自定义ViewGroup不难,它就要求你会用两个方法去测量和摆放,难的是什么呢?难的是你要怎么去写算法来完成你这个viewgroup的实现,也就是两个方法中具体的代码实现,还有就是这两个方法连起来的效果和与LayoutParams配合的效果,主要是onMeasure和onLayout的配合,要非常的注意细节,比如你在onLayout设置间距,但是在onMeasure没有去开辟这个间距所需要的空间,那就会出问题,这种写多就会清楚了。

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

推荐阅读更多精彩内容