在 Android 中,要自定義 ViewGroup,您需要繼承 ViewGroup 類并重寫其 onLayout() 和 onMeasure() 方法。以下是一個簡單的示例,展示了如何創建一個自定義的 ViewGroup,該 ViewGroup 將其子視圖按照“之”字形排列。
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
public class ZigzagViewGroup extends ViewGroup {
public ZigzagViewGroup(Context context) {
super(context);
}
public ZigzagViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ZigzagViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = 0;
int height = 0;
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
measureChild(child, widthMeasureSpec, heightMeasureSpec);
width = Math.max(width, child.getMeasuredWidth());
height += child.getMeasuredHeight();
}
setMeasuredDimension(resolveSize(width, widthMeasureSpec), resolveSize(height, heightMeasureSpec));
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int currentTop = t;
int currentWidth = getMeasuredWidth();
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
if (i % 2 == 0) {
child.layout(l, currentTop, l + childWidth, currentTop + childHeight);
currentTop += childHeight;
} else {
child.layout(r - childWidth, currentTop, r, currentTop + childHeight);
currentTop += childHeight;
}
}
}
現在,您可以在布局文件中使用自定義的 ZigzagViewGroup:
<your.package.name.ZigzagViewGroup
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Child 1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Child 2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Child 3" />
<!-- Add more child views as needed -->
</your.package.name.ZigzagViewGroup>
這只是一個簡單的示例,您可以根據自己的需求進一步自定義 ViewGroup。例如,您可以更改子視圖的排列方式、添加額外的布局約束等。