onLayout()方法的目的:将ViewGroup里的每一个子View放置在一定的位置。
实现思路:在onLayout()方法里获取子View的实例,然后通过调用View.layout(int l, int t, int r, int b)实现子View在ViewGroup里的精确放置。
自定义View首先调用onMeasure进行测量,然后调用onLayout方法,动态获取子View和子View的测量大小,可以根据View的测量大小确定View在ViewGroup中的“左上点”和“右下点”精确位置坐标,以将View精确的放置在ViewGroup中特定的位置。
onLayout方法:
@Override
protected abstract void onLayout(boolean changed, int l, int t, int r, int b);
该方法在ViewGroup中定义是抽象函数,继承ViewGroup必须重写onLayout方法,而ViewGroup的onMeasure并非必须重写的。
参数l,t,r,b分别是放置ViewGroup的矩形可用空间(除去margin和padding的空间)的左上角的left、top以及右下角right、bottom值。
layout方法:
public void layout(int l, int t, int r, int b);
调用该方法需要传入放置View的矩形空间左上角left、top值和右下角right、bottom值。这四个值是相对于父控件而言的。例如传入的是(10, 10, 100, 100),则该View在距离父控件的左上角位置(10, 10)处显示,显示的大小是宽高是90。
平常开发所用到RelativeLayout、LinearLayout、FrameLayout…这些都是继承ViewGroup的布局。这些布局的实现都是通过都实现ViewGroup的onLayout方法,只是实现方法不一样而已。
例如举一个简单的例子:写一个布局,将其中的View的长宽都设置为100dp(其实长宽应该是经过onMeasure方法拿取准确的长宽值,这里只是为了集中精力介绍onLayout方法,所以简单化了),由左向右依次排列,并且每个View之间相距20dp。
效果如下:
xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.dong.demo.CustomGroup
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#000000">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ff00" />
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0000" />
</com.example.dong.demo.CustomGroup>
</LinearLayout>
先在纸上根据想要的效果运算一下坐标点的坐标:
上CustomGroup的java代码:
/**
* 将ViewGroup中每一个子View放置在特定的位置
*/
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
//得到子View的数量
int size = getChildCount();
for (int i = 0; i < size; i++) {
//拿取第i个子View
View view = getChildAt(i);
//通过子View的“左上点坐标”和“右下点坐标”将它精确的放置在ViewGroup的特定位置上
view.layout(i*dip2px(mContext,120f),0,(dip2px(mContext,120f)*i+dip2px(mContext,100f)),dip2px(mContext,100f));
}
}
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}