onLayout()與自定義View布局實(shí)現(xiàn)

小樊
82
2024-08-14 07:19:39

onLayout()方法是ViewGroup類(lèi)中的一個(gè)重要方法,用于確定子View的位置和大小。當(dāng)一個(gè)ViewGroup的子View發(fā)生變化時(shí),系統(tǒng)會(huì)調(diào)用onLayout()方法來(lái)重新布局子View。

自定義View的布局實(shí)現(xiàn)可以通過(guò)重寫(xiě)onLayout()方法來(lái)實(shí)現(xiàn)。在自定義View中,可以在onLayout()方法中設(shè)置子View的位置和大小,以實(shí)現(xiàn)自定義的布局效果。

例如,假設(shè)我們有一個(gè)自定義的LinearLayout,需要實(shí)現(xiàn)子View按照一定的規(guī)則進(jìn)行布局。我們可以重寫(xiě)LinearLayout的onLayout()方法,然后在方法中設(shè)置子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);
        
        // 自定義布局規(guī)則
        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;
        }
    }
}

在上面的例子中,我們重寫(xiě)了LinearLayout的onLayout()方法,實(shí)現(xiàn)了一個(gè)自定義的布局規(guī)則:子View依次垂直排列,頂部對(duì)齊。在方法中,我們遍歷子View,設(shè)置每個(gè)子View的位置和大小。

通過(guò)重寫(xiě)onLayout()方法,我們可以實(shí)現(xiàn)各種自定義的布局效果,從而滿(mǎn)足不同的設(shè)計(jì)需求。

0