自定义ViewGroup,就是组合型控件,ViewGroup不需要调用ONDraw()方法,因为ViewGroup就是View的容器,每一个View是其的子类,只需要将创建好的View添加到ViewGroup控件当中即可。
在自定义ViewGroup控件,首先确定是否从Layout(布局文件中)调用,就一定要调用该方法,用于实例化从layout布局文件中加载组件。
public MyViewGroup(Context context, AttributeSet attrs) { super(context, attrs); }
如果在子布局文件中添加有新的组件,比如Button,ImageView,ListView 等组件,必然自定义类会调用该方法,该方法用于测绘在子控件中子组件的位置。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
ViewGroup添加到组件,就会在该方法中确定组件的位置,该方法描述的就是子控件在父控件中的位置大小,信息等。
protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
}
效果图:实现上下滑动效果
说了那么多,下面直接上代码:
这是向ViewGroup类对象中添加对象ImageView
package com.example.demod3;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import