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没有去开辟这个间距所需要的空间,那就会出问题,这种写多就会清楚了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值