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)
}
總結
以上是生活随笔為你收集整理的android 自定义控件viewgroup,Android自定义控件ViewGroup的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 德祥隆闻喜煮饼一个多少克?
- 下一篇: 如何监控Android电视桌面,andr