美文网首页Android 开发Android自定义View程序员
自定义ViewGroup实现view的自由布局

自定义ViewGroup实现view的自由布局

作者: HJXANDHMR | 来源:发表于2016-08-11 09:24 被阅读479次

    前段时间有个需求是:

    1. 给定一个list 数组,根据集合里面的数据来画View;
    2. View的数目是小于等于手机横屏后的宽度。

    传统的线性布局,相对布局都不能满足这个需求,所以我们只能自己来自定义一个ViewGroupl 。

    自定义ViewGroup

    我们知道ViewGroup就是View的容器类,我们经常用的LinearLayout,RelativeLayout等都是ViewGroup的子类。

    CustomViewGroup.java

    public class CustomViewGroup extends ViewGroup {
    
        private final static String TAG = "CustomViewGroup";
    
        // view 的间隔
        private final static int VIEW_MARGIN = 0;
    
        public CustomViewGroup(Context context) {
            super(context);
        }
    
        // 重写它的onMeasure() 在该方法中进行对子View的大小进行测量
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    
            Log.d(TAG, "widthMeasureSpec = " + widthMeasureSpec
                    + " heightMeasureSpec" + heightMeasureSpec);
            for (int index = 0; index < getChildCount(); index++) {
                final View child = getChildAt(index);
                child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
            }
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    
        // 重写onLayout方法实现子View的定位
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
    
            Log.d(TAG, "changed = " + changed + " left = " + l + " top = " + t
                    + " right = " + r + " botom = " + b);
            final int count = getChildCount();
            int row = 0;
            //当前宽度
            int lengthX = l;
            //当前高度
            int lengthY = t;
            for (int i = 0; i < count; i++) {
                final View child = this.getChildAt(i);
                int width = child.getMeasuredWidth();
                int height = child.getMeasuredHeight();
                lengthX += width + VIEW_MARGIN;
                lengthY = row * (height + VIEW_MARGIN) + VIEW_MARGIN + height
                        + t;
                if (lengthX > r) {
                    lengthX = width + VIEW_MARGIN + l;
                    row++;
                    lengthY = row * (height + VIEW_MARGIN) + VIEW_MARGIN + height
                            + t;
                }
                child.layout(lengthX - width, lengthY - height, lengthX, lengthY);
            }
        }
    }
    

    MainActivity.java

    public class MainActivity extends Activity {
        private CustomViewGroup mViewGroup;
        private ArrayList<ViewSizeInfo> mViewSizes;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            //初始化数据
            mViewSizes = getViewSizes();
            mViewGroup = getViewGroup(mViewSizes);
            setContentView(mViewGroup);
        }
    
        private ArrayList<ViewSizeInfo> getViewSizes() {
            ArrayList<ViewSizeInfo> viewSizes = new ArrayList<>();
    
            viewSizes.add(new ViewSizeInfo(1, 1,R.color.colorAccent));
            viewSizes.add(new ViewSizeInfo(3, 2,R.color.colorDarkOrchid));
            viewSizes.add(new ViewSizeInfo(4, 4,R.color.colorPrimary));
            viewSizes.add(new ViewSizeInfo(1, 5,R.color.colorLightBLue));
            return viewSizes;
        }
    
        private CustomViewGroup getViewGroup(ArrayList<ViewSizeInfo> viewSizes) {
            CustomViewGroup myViewGroup = new CustomViewGroup(this);
    
            myViewGroup.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            int width = ScreenUtil.getScreenWidth(this)/10;
            int height =ScreenUtil.getScreenHeight(this)/5;
    
            for (int i = 0; i <viewSizes.size() ; i++) {
                ViewSizeInfo viewSize =viewSizes.get(i);
                TextView textView = new TextView(this);
                textView.setText("TextView"+i);
                textView.setBackgroundColor(getResources().getColor(viewSize.getColor()));
                textView.setWidth(width* viewSize.getWidth());
                textView.setHeight(height* viewSize.getHeight());
                myViewGroup.addView(textView);
            }
            return myViewGroup;
        }
    }
    

    ViewSizeInfo.java

    public class ViewSizeInfo {
        private int mWidth;
        private int mHeight;
        // 设置默认颜色
        private int color;
    
        public ViewSizeInfo(int width, int height) {
            this.mWidth = width;
            this.mHeight = height;
        }
    
        public ViewSizeInfo(int width, int height, int color) {
            this.mWidth = width;
            this.mHeight = height;
            this.color = color;
        }
    
        public int getWidth() {
            return mWidth;
        }
    
        public void setWidth(int width) {
            this.mWidth = width;
        }
    
        public int getHeight() {
            return mHeight;
        }
    
        public void setHeight(int height) {
            this.mHeight = height;
        }
    
        public int getColor() {
            return color;
        }
    
        public void setColor(int color) {
            this.color = color;
        }
    }
    

    ScreenUtil.java

    public class ScreenUtil {
        private ScreenUtil() {
            /*cannot be instantiated*/
            throw new UnsupportedOperationException("cannot be instantiated");
        }
    
        /**
         * 获得屏幕宽度
         *
         * @param context
         * @return
         */
        public static int getScreenWidth(Context context) {
            WindowManager wm = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics outMetrics = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(outMetrics);
            return outMetrics.widthPixels;
        }
    
        /**
         * 获得屏幕高度
         *
         * @param context
         * @return
         */
        public static int getScreenHeight(Context context) {
            WindowManager wm = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics outMetrics = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(outMetrics);
            return outMetrics.heightPixels;
        }
    }
    
    

    效果图

    完整代码已经上传到Github了:https://github.com/HJXANDHMR/CustomViewGroup

    相关文章

      网友评论

      • Swy2w:自定义View好难啊:dizzy_face:
      • 醉酒肆之:怎奈实用性不足
        HJXANDHMR:@醉酒肆之 哈哈,学的是思路,不是直接拿过来就可以用的。
      • 小鹿风:哟哟哟切克闹
        HJXANDHMR:@小鹿风 煎饼果子来一套

      本文标题:自定义ViewGroup实现view的自由布局

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