Android自定义布局ViewGroup

2021-03-24  本文已影响0人  陆笪_刑道荣

概念

基本用法

public class MyViewGroup extends ViewGroup { 

    public MyViewGroup(Context context) { 

        super(context); 

        initChilren(context);   //向容器中添加孩子

    } 

    private void initChilren (Context context) { 

        Button aBtn = new Button(context);

        this.addView(aBtn); 

        Button bBtn = new Button(context);

        this.addView(bBtn); 

    }

    @Override

    protected void onLayout(boolean changed, int l, int t, int r, int b)

{ 

    //对容器的孩子进行布局。

    child.measure(r - l, b - t); 

    child.layout(0, 50, child.getMeasuredWidth(), child .getMeasuredHeight() + 50); 

     }
}

常用方法

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec, heightMeasureSpec);
    }

2.onLayout()方法中,通过view.layout(left,right,top,bottom)。
layout方法会设置该View视图位于父视图的坐标轴
其中left:子布局的左侧到父布局左侧的距离,right:子布局的右侧到父布局左侧的距离,top:子布局的上侧到父布局上侧的距离,bottom:子布局的下侧到父布局上侧的距离。

上一篇 下一篇

猜你喜欢

热点阅读