美文网首页Android自定义View
自定义View(6) -- 流式布局

自定义View(6) -- 流式布局

作者: 曾大稳丶 | 来源:发表于2017-06-17 13:55 被阅读0次

    先看效果图:


    tagLayout

    上几次都是自定义的view,这期我们来自定义一个简单的ViewGroup。和自定义view不同的是,viewGroup一般情况下是管理childView,所以主要是重写onMeause()来测量childView宽高,从而设置自身宽高,然后重写onLayout来摆放childView的位置,我们一般不对viewGroup进行绘制,如果特殊情况需要绘制,重写dispatchDraw()来进行重绘,因为viewGroup在不设置设置背景的情况下是不会调用onDraw()的,具体请看源码。


    接下来进行我们这篇文章的主题,先理清楚思路,我们实现的效果就是一个容器里面的childView挨着挨着的从左往右摆放,如果摆放的时候这个childView的宽度加上这行前面的childView宽度大于当前设置的宽度的时候,那么就需要换行。
    初始化和属性我就不说了,如需要可以自行添加,这里我们要考略到childViewmargin,所以我们仿照LinearLayout来重写generateLayoutParams函数来设置一个带有margin属性的LayoutParams

      // 设置自己需要的LayoutParams
        @Override
        public LayoutParams generateLayoutParams(AttributeSet attrs) {
            return new MarginLayoutParams(getContext(), attrs);
        }
    

    重写onMeause()来进行childView的遍历测量,并且设置自生的宽高,因为我们考略到下面要重写onLayout来摆放childView的位置,难免会有一番计算,我们为了不重复计算,所以写了一个List来进行对childView以行为单位来组装,具体如下

     private List<List<View>> mChildViews = new ArrayList<>();
        // 指定宽高
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            // 清空集合
            mChildViews.clear();
    
            int childCount = getChildCount();
    
            // 获取到宽度
            int width = MeasureSpec.getSize(widthMeasureSpec);
    
            // 高度需要计算
            int height = getPaddingTop() + getPaddingBottom();
    
            // 一行的宽度
            int lineWidth = getPaddingLeft();
    
            ArrayList<View> childViews = new ArrayList<>();
            mChildViews.add(childViews);
    
            // 子View高度不一致的情况下
            int maxHeight = 0;
            for (int i = 0; i < childCount; i++) {
                // for循环测量子View
                View childView = getChildAt(i);
                if (childView.getVisibility() == GONE) {
                    continue;
                }
                // 这段话执行之后就可以获取子View的宽高,因为会调用子View的onMeasure
                measureChild(childView, widthMeasureSpec, heightMeasureSpec);
                // margin值 ViewGroup.LayoutParams 没有 就用系统的MarginLayoutParams
                // LinearLayout有自己的 LayoutParams  会复写一个非常重要的方法
                MarginLayoutParams params = (MarginLayoutParams) childView.getLayoutParams();
                // 什么时候需要换行,一行不够的情况下 考虑 margin
                if (lineWidth + (childView.getMeasuredWidth() + params.rightMargin + params.leftMargin) > width) {
                    // 换行,累加高度  加上一行条目中最大的高度
                    height += maxHeight;
    
                    //下面重新初始化
                    maxHeight = childView.getMeasuredHeight() + params.bottomMargin + params.topMargin;
                    lineWidth = childView.getMeasuredWidth() + params.rightMargin + params.leftMargin;
                    childViews = new ArrayList<>();
                    mChildViews.add(childViews);
                } else {
                    lineWidth += childView.getMeasuredWidth() + params.rightMargin + params.leftMargin;
                    maxHeight = Math.max(childView.getMeasuredHeight() + params.bottomMargin + params.topMargin, maxHeight);
                }
                childViews.add(childView);
            }
            height += maxHeight;//不要忘记最后一行的高度
    
    //        Log.e("TAG", "width -> " + width + " height-> " + height);
            // 根据子View计算和指定自己的宽高
            setMeasuredDimension(width, height);
        }
    

    然后我们根据上面的组装的List数据来进行对childView进行摆放

     @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            int left, top = getPaddingTop(), right, bottom;
    
            for (List<View> childViews : mChildViews) {
                left = getPaddingLeft();
                int maxHeight = 0;
                for (View childView : childViews) {
                    if (childView.getVisibility() == GONE) {
                        continue;
                    }
                    MarginLayoutParams params = (MarginLayoutParams) childView.getLayoutParams();
                    left += params.leftMargin;
                    int childTop = top + params.topMargin;
                    right = left + childView.getMeasuredWidth();
                    bottom = childTop + childView.getMeasuredHeight();
    //                Log.e("TAG", "left -> " + left + " top-> " + childTop + " right -> " + right + " bottom-> " + bottom);
                    // 摆放
                    childView.layout(left, childTop, right, bottom);
                    // left 叠加
                    left += childView.getMeasuredWidth() + params.rightMargin;
                    // 不断的叠加top值
                    int childHeight = childView.getMeasuredHeight() + params.topMargin + params.bottomMargin;
                    maxHeight = Math.max(maxHeight, childHeight);
                }
                top += maxHeight;
            }
        }
    

    主要的逻辑代码已经写的很清楚了,细致一看就能很容易的理解。这样的画效果就实现了,但是我们在实际开发的过程中,一般是后台获取到一个List数据,然后我们在设置值,这里推荐一个设计模式就是Adapter模式。这样的话我们就可以自定义自己的View,轻松的降低了代码的耦合,并且复用效果也好,我们申明一个`Adapter'类

    /**
     * Email 240336124@qq.com
     * Created by Darren on 2017/6/11.
     * Version 1.0
     * Description: 流式布局的Adapter
     */
    public abstract class BaseAdapter {
    
        // 1.有多少个条目
        public abstract int getCount();
    
        // 2.getView通过position
        public abstract View getView(int position,ViewGroup parent);
    
    }
    

    这里就简单写了,然后我们在容器中添加setAdapter()函数

     /**
         * 设置Adapter
         *
         * @param adapter
         */
        public void setAdapter(BaseAdapter adapter) {
            if (adapter == null) {
                throw new NullPointerException("adapter is null");
            }
            // 清空所有子View
            removeAllViews();
            mAdapter = adapter;
            // 获取数量
            int childCount = mAdapter.getCount();
            for (int i = 0; i < childCount; i++) {
                // 通过位置获取View
                View childView = mAdapter.getView(i, this);
                addView(childView);
            }
        }
    

    然后我们使用就和ListView类似了:

     private TagLayout mTagLayout;
    
        private List<String> mItems;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_taglayout);
            mTagLayout = (TagLayout) findViewById(R.id.taglayout);
    
            mItems = new ArrayList<>();
    
            for (int i = 0; i < 20; i++) {
                mItems.add("ABC"+i);
            }
            mTagLayout.setAdapter(new BaseAdapter() {
                @Override
                public int getCount() {
                    return mItems.size();
                }
    
                @Override
                public View getView(int position, ViewGroup parent) {
                    TextView tagTv = (TextView) LayoutInflater.from(TagLayoutActivity.this)
                            .inflate(R.layout.item_tag, parent, false);
                    tagTv.setText(mItems.get(position));
                    // 操作ListView的方式差不多
                    return tagTv;
                }
            });
        }
    

    这样的话我们就简单的实现了流式布局的效果,如果需要单选多选之类的,在这基础上添加就可以了。
    接下来再具体的总结下自定义view和自定义viewGroup的套路:

    View的自定义套路
    1. 初始化,自定义属性,获取自定义属性(配置属性)
    2. onMeasure()方法用于测量计算自己的宽高,前提是继承自View,如果是继承自系统已有的 TextView , Button,已经给你计算好了宽高,就可以跳过这个步骤(设置宽高)
    3. onDraw() 用于绘制自己的显示(View绘制)
    4. onTouch() 用于与用户交互(事件分发)

    ViewGroup的自定义套路
    1. 自定义属性,获取自定义属性,很少有这种需求(配置属性)
      2.onMeasure()方法,for循环测量子View,根据子View的宽高来计算自己的宽高(设置宽高)
    2. onLayout()用来摆放子View,前提是不是GONE的情况
    3. onDraw()一般不需要,默认情况下是不会调用,如果你要绘制需要实现dispatchDraw()方法(View绘制)
    4. 在很多情况下不会继承自ViewGroup ,往往是继承 系统已经提供好的ViewGroupViewPager ScrollView RelativeLayout,这样的话onMeause() onLayout()一般都可以跳过,相应的重写一些方法来实现自己的需求。比如侧滑菜单可以继承LinearLayout 或者RelativeLayout等来重写onInterceptTouchEvent来实现。

    这篇文章到这就结束了 ,希望对大家有所提升。

    下载地址:https://github.com/ChinaZeng/CustomView

    相关文章

      网友评论

        本文标题:自定义View(6) -- 流式布局

        本文链接:https://www.haomeiwen.com/subject/ugapqxtx.html