Androidでビューグループをカスタマイズする方法
要自定义一个ViewGroup,你需要创建一个继承自ViewGroup的子类,并重写一些关键的方法来定义你的布局和子视图的排列方式。
カスタマイズした ViewGroup を作成する手順に入るにあたってのわかりやすい例を示します。
- カスタムViewGroupという新しいJavaクラスを作成し、ViewGroupクラスを継承します
public class CustomViewGroup extends ViewGroup {
public CustomViewGroup(Context context) {
super(context);
}
public CustomViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// 在这里定义子视图的排列方式和位置
int childCount = getChildCount();
int childLeft = getPaddingLeft();
int childTop = getPaddingTop();
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
int childWidth = childView.getMeasuredWidth();
int childHeight = childView.getMeasuredHeight();
childView.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
childLeft += childWidth;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 在这里定义ViewGroup的尺寸
int desiredWidth = 0;
int desiredHeight = 0;
int childCount = getChildCount();
// 测量每个子视图的尺寸
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
measureChild(childView, widthMeasureSpec, heightMeasureSpec);
desiredWidth += childView.getMeasuredWidth();
desiredHeight = Math.max(desiredHeight, childView.getMeasuredHeight());
}
// 添加上ViewGroup的padding和边距
desiredWidth += getPaddingLeft() + getPaddingRight();
desiredHeight += getPaddingTop() + getPaddingBottom();
// 根据计算结果设置ViewGroup的尺寸
setMeasuredDimension(resolveSize(desiredWidth, widthMeasureSpec), resolveSize(desiredHeight, heightMeasureSpec));
}
}
- カスタム ViewGroup をレイアウトファイルで使用できるようになりました。XML レイアウトファイルでは、を使用してカスタム ViewGroupを宣言します。
<你的包名.CustomViewGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<!-- 在这里添加子视图 -->
</你的包名.CustomViewGroup>
上記の例は単純なカスタムViewGroupの一例です。onLayoutメソッド内で、その中のビューの配置方法(水平配置や垂直配置など)を定義できます。onMeasureメソッド内でカスタムViewGroupの大きさを定義することもできます。これらのメソッドを上書きすることにより、ニーズに応じたカスタムViewGroupを様々に作成できます。