Android自定义ViewGroup

package com.mapbar.adas.camera;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by sunxx on 2018/2/27.
 */

public class MyViewGroup extends ViewGroup {
    private String TAG = "CAM";

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

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //这里有MeasureSpec
        //MeasureSpec.getMode(MeasureSpec.AT_MOST);
        int count = getChildCount();
        //measureChildren方法测量所有的子view
        //measureChildren(widthMeasureSpec, heightMeasureSpec);
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            //测量单个的子view
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
        }

    }

    /**
     * @param changed
     * @param l
     * @param t
     * @param r
     * @param b
     */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        Log.i(TAG, "数量" + getChildCount());
        //得到每个子view分别根据宽高排列固定位置
        //这里写了4个view分别为屏幕的4个角落
        int count = getChildCount();
        int height = 0;
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
//            child.layout(0, height, child.getMeasuredWidth(), child.getMeasuredHeight()+height);
//            height+=child.getHeight();
            switch (i) {
                case 0:
                    child.layout(0, 0, child.getMeasuredWidth(), child.getMeasuredHeight());
                    break;
                case 1:
                    child.layout(getWidth() - child.getMeasuredWidth(), 0, getWidth(), child.getMeasuredHeight());
                    break;
                case 2:
                    child.layout(0, getHeight() - child.getMeasuredHeight(), child.getMeasuredWidth(), getHeight());
                    break;
                case 3:
                    child.layout(getWidth() - child.getMeasuredWidth(), getHeight() - child.getMeasuredHeight(), getWidth(), getHeight());
                    break;
            }
        }
    }

    /**
     * @deprecated {@link #MyViewGroup(Context)}
     */
    public void init() {

    }

    /**
     * @param a
     * @see #init() 参考init过时方法
     */
    public void newinit(int a) {

    }
}

你可能感兴趣的:(Android)