一般在继承 ViewGroup 的时候,重写 onLayout 方法,设置子布局的位置
这个例子是设置 offsetLayout 子布局的位置
效果图如下:
实现步骤:
1.自定义控件 OffsetLayout
package com.zhh.android;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
/**
* onLayout 设置子布局的位置
* Created by 16838 on 2019/6/1.
*/
public class OffsetLayout extends AbsoluteLayout {
private int mOffsetHorizontal = 0; // 水平方向的偏移量
private int mOffsetVertical = 0; // 垂直方向的偏移量
public OffsetLayout(Context context) {
super(context);
}
public OffsetLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
// 重写onLayout方法,意在调整下级视图的方位
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i); // 获得第i个子视图
if (child.getVisibility() != GONE) {
// 计算子视图的左边偏移数值
int new_left = (r - 1) / 2 - child.getMeasuredWidth() / 2 + mOffsetHorizontal;