public class MyViewGroup extends ViewGroup {
private int width;
private int height;
public MyViewGroup(Context context) {
super(context);
}
public MyViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width=getDefaultSize(getSuggestedMinimumWidth(),widthMeasureSpec);
height=getDefaultSize(getSuggestedMinimumHeight(),heightMeasureSpec);
measureChildren(width,height);//测量整体的宽和高
}
@Override
protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
//i,i1为左上角。i2,i3为右下角
View child1=getChildAt(0);
View child2=getChildAt(1);
View child3=getChildAt(2);
View child4=getChildAt(3);
if (child1!=null){
child1.layout(0,0,child1.getMeasuredWidth(),child1.getMeasuredHeight());
}
if (child2!=null){
child2.layout(i2-child2.getMeasuredWidth(),0,i2,child2.getMeasuredHeight());
}
if (child3!=null){
child3.layout(0,i3-child3.getMeasuredHeight(),child3.getMeasuredWidth(),i3);
}
if (child4!=null){
child4.layout(i2-child4.getMeasuredWidth(),i3-child4.getMeasuredHeight(),i2,i3);
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity">
<com.lingzhuo.test.myviewgroup.MyViewGroup
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="150dp"
android:layout_height="200dp" />
<Button
android:layout_width="150dp"
android:layout_height="200dp" />
<Button
android:layout_width="150dp"
android:layout_height="200dp" />
<Button
android:layout_width="150dp"
android:layout_height="200dp" />
</com.lingzhuo.test.myviewgroup.MyViewGroup>
</RelativeLayout>
自定义ViewGroup
最新推荐文章于 2021-12-08 15:31:19 发布
本文介绍了一种自定义ViewGroup的实现方式,通过重写onMeasure和onLayout方法来控制子视图的位置和大小。具体实现了四个按钮分别位于屏幕的四个角落。
4836

被折叠的 条评论
为什么被折叠?



