zoukankan      html  css  js  c++  java
  • 最简单的自定义ViewGroup

    FlowLayout

    子View们的宽度加起来超过一行,会自动换行显示。

    核心就两步:

    • 在Layout中的onMeasure方法中调用子View的measure(),这儿虽然用的是measureChild方法,但最终还是去调用子View的measure()
    • 在Layout中的onLayout方法中调用子View的layout()



    再复杂的自定义View都是这样从最简单的形式,不断增加代码,迭代出来的




    最简单的自定义ViewGroup:

    public class FlowLayout extends ViewGroup {
    
        public FlowLayout(Context context) {
            this(context, null);
        }
    
        public FlowLayout(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
        }
    
        public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            int childCount = getChildCount();
            for (int i = 0; i < childCount; i++) {
                measureChild(getChildAt(i), widthMeasureSpec, heightMeasureSpec);
            }
        }
    
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            int childCount = getChildCount();
            int layoutWidth = r-l;
            int left = 0;
            int right = 0;
            int top = 0;
            for (int i = 0; i < childCount; i++) {
                View view = getChildAt(i);
                // 换行:比较right,right如果大于Layout宽度,那么要换行
                right = left + view.getMeasuredWidth();
                if (right > layoutWidth) {
                    left = 0;
                    right = left + view.getMeasuredWidth();
                    top += view.getMeasuredHeight();
                }
                getChildAt(i).layout(left, top, right, top + view.getMeasuredHeight());
                left += view.getWidth();
            }
        }
    
    }
    
    


    在最简单的实现下,我们可以考虑更多,当然代码也就更多,如:

    • 处理子View不可见的情况
    • 添加对MeasureSpec.AT_MOST的支持
    • 添加对layout_margin的支持


    上述这些我也都实现了,但还有一个我没有去弄,对gravity的支持(因为其非必需就暂时不加,我现有其它事),如果你有兴趣完成它,可以fork,弄好了pull request。


    完整代码查看

  • 相关阅读:
    在程序中向水晶报表传参数,以及在程序中指定报表源
    运行Web程序时提示无法使用调试
    TreeView控件节点重命名后没有进入beginEdit的解决方案
    网络负载平衡(转)
    纵横表转交叉表
    重绘datagrid,包括强迫显示某行
    datagrid添加事件
    我的页面模板算法
    C++函数重载
    关于string.empty 与 "" 内存分配
  • 原文地址:https://www.cnblogs.com/duan-xue-bin/p/12169208.html
Copyright © 2011-2022 走看看