700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > android 自定义控件viewgroup Android自定义控件ViewGroup

android 自定义控件viewgroup Android自定义控件ViewGroup

时间:2022-05-10 03:25:51

相关推荐

android 自定义控件viewgroup Android自定义控件ViewGroup

1.自定义ViewGroup第一步重写OnMeasure方法;

在onMeasure方法中一般情况下我们会利用父类传给我们的参数(int widthMeasureSpec, int heightMeasureSpec)来

获取Mode和Size:

final int widthMode = MeasureSpec.getMode(widthMeasureSpec);

final int heightMode = MeasureSpec.getMode(heightMeasureSpec);

int widthSize = MeasureSpec.getSize(widthMeasureSpec);

int heightSize = MeasureSpec.getSize(heightMeasureSpec);

之后可以调用int childCount = getChildCount();

获取子元素数量

for (int i = 0; i < childCount; i++) {

View child = getChildAt(i);

LayoutParams lp = child.getLayoutParams();

int childWidthSpec = getChildMeasureSpec(widthMeasureSpec, 0, lp.width);

int childHeightSpec = getChildMeasureSpec(heightMeasureSpec, 0, lp.height);

child.measure(childWidthSpec, childHeightSpec);

}

然后父元素的widthMode 和heightMode 计算自身的尺寸

switch (widthMode) {

case MeasureSpec.EXACTLY:

相当于父布局中match_parent,那么自身尺寸就可以等于widthSize

而其他情况则需要根据自己的需求判断

}

switch (heightMode) {

高度同理

}

最后一定要调用

setMeasuredDimension(width, height);//保存自身

2.自定义ViewGroup第二步重写onLayout方法;

其中方法的四个参数boolean changed, int l, int t, int r, int b是相对父容器的相对位置

利用child.getMeasuredWidth()及child.getMeasuredHeight()获取大小就可以计算位置

最后利用child.layout(left, top, right, bottom)方法摆放控件

int childCount = getChildCount();

for (int i = 0; i < childCount; i++) {

View child = getChildAt(i)

child.getMeasuredWidth();

child.getMeasuredHeight();

child.layout(left, top, right, bottom)

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。