美文网首页
Android自定义布局ViewGroup

Android自定义布局ViewGroup

作者: 陆笪_刑道荣 | 来源:发表于2021-03-24 09:54 被阅读0次

概念

  • 在Android中,View比视图具有更广的含义,它包含了用户交互和显示,更像Windows操作系统中的window。
    ViewGroup是View的子类,所以它也具有View的特性,但它主要用来充当View的容器,将其中的View视作自己的孩子,对它的子View进行管理,当然它的孩子也可以是ViewGroup类型。
    ViewGroup(树根)和它的孩子们(View和ViewGroup)以树形结构形成了一个层次结构,View类有接受和处理消息的功能,android系统所产生的消息会在这些ViewGroup和 View之间传递。

基本用法

  • 可以调用其成员函数addView()将View当作孩子放到ViewGroup中。
    我们经常使用的LinearLayout、relativeLayout等都是ViewGroup的子类,ViewGroup类中有一个内部类ViewGroup.LayoutParams,我们经常使用LayoutParams的子类来构造布局参数。
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); 

     }
}

常用方法

  • onMesure() ——计算childView的测量值以及模式,以及设置自己的宽和高。
  • onLayout()——通过getChildCount()获取子view数量,getChildAt获取所有子View,分别调用layout(int l, int t, int r, int b)确定每个子View的摆放位置。
    1.onMesure()方法中,基本是使用子View的宽高,来确定自己的宽高。子布局的宽高可以在子View中设置。所以大多数情况之下,我们使用以下方法:
@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:子布局的下侧到父布局上侧的距离。

相关文章

网友评论

      本文标题:Android自定义布局ViewGroup

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