租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

onLayout()与自定义View布局实现,tablayout自定义

发布时间:2024-08-14 07:19:39

onLayout()与自定义View布局实现

onLayout()方法是ViewGroup类中的一个重要方法,用于肯定子View的位置和大小。当一个ViewGroup的子View产生变化时,系统会调用onLayout()方法来重新布局子View。

自定义View的布局实现可以通太重写onLayout()方法来实现。在自定义View中,可以在onLayout()方法中设置子View的位置和大小,以实现自定义的布局效果。

例如,假定我们有一个自定义的LinearLayout,需要实现子View依照一定的规则进行布局。我们可以重写LinearLayout的onLayout()方法,然后在方法中设置子View的位置和大小。

public class CustomLinearLayout extends LinearLayout {

    public CustomLinearLayout(Context context) {
        super(context);
    }

    public CustomLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        
        // 自定义布局规则
        int childCount = getChildCount();
        int top = 0;
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();
            child.layout(0, top, childWidth, top + childHeight);
            top += childHeight;
        }
    }
}

在上面的例子中,我们重写了LinearLayout的onLayout()方法,实现了一个自定义的布局规则:子View顺次垂直排列,顶部对齐。在方法中,我们遍历子View,设置每一个子View的位置和大小。

通太重写onLayout()方法,我们可以实现各种自定义的布局效果,从而满足区分的设计需求。

TikTok千粉号购买平台:https://tiktokusername.com/