我有一个自定义视图组,它扩展了relativelayout,我有几个组件。由于嵌套权重布局的糟糕表现,我决定以编程方式设置子视图的大小和位置。现在,我使用xml创建视图和子视图,然后以编程方式设置其中一些的位置和大小,如下所示。
private void assignProperSizeToChildren(int x, int y) {
int cardWidth = x / 3;
int cardHeight = y / 3;
LayoutParams layoutParams = (LayoutParams) bgView1.getLayoutParams();
layoutParams.topMargin = (int)(y / 4 * (1 - val));
layoutParams.height = cardHeight;
layoutParams.width = cardWidth;
LayoutParams layoutParams2 = (LayoutParams) bgView2.getLayoutParams();
layoutParams2.topMargin = (int)(y / 4 * (1 - val));
layoutParams2.height = cardHeight;
layoutParams2.width = cardWidth;
LayoutParams layoutParams3 = (LayoutParams) bgView3.getLayoutParams();
layoutParams3.topMargin = (int)(y * 3 / 8 * (1 - val));
layoutParams3.height = cardHeight;
layoutParams3.width = cardWidth;
bgView1.setLayoutParams(layoutParams);
bgView2.setLayoutParams(layoutParams2);
bgView3.setLayoutParams(layoutParams3);
bgView1.setPivotY(y / 2);
bgView2.setPivotY(y / 2);
bgView3.setPivotY(y / 2);
View view = findViewById(R.id.bg);
RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) view.getLayoutParams();
layoutParams1.topMargin = y / 6;
layoutParams1.bottomMargin = y / 6;
layoutParams1.leftMargin = x / 6;
layoutParams1.rightMargin = x / 6;
view.setLayoutParams(layoutParams1);
LinearLayout.LayoutParams layoutParams4 = (LinearLayout.LayoutParams) receiveProgress.getLayoutParams();
layoutParams4.width = cardWidth;
receiveProgress.setLayoutParams(layoutParams4);
layoutParams4 = (LinearLayout.LayoutParams) sendProgress.getLayoutParams();
layoutParams4.width = cardWidth;
sendProgress.setLayoutParams(layoutParams4);
name.setTextSize(TypedValue.COMPLEX_UNIT_PX, y / 7);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int x = MeasureSpec.getSize(widthMeasureSpec);
int y = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(widthMeasureSpec,heightMeasureSpec);
assignProperSizeToChildren(x,y);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
它似乎有效,但当我想做动画时,视图表现得很奇怪。
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float val = (Float) valueAnimator.getAnimatedValue();
LayoutParams layoutParams = (LayoutParams) bgView1.getLayoutParams();
layoutParams.topMargin = (int) (getMeasuredHeight() / 4 * (1 - val));
bgView1.setLayoutParams(layoutParams);
LayoutParams layoutParams2 = (LayoutParams) bgView2.getLayoutParams();
layoutParams2.topMargin = (int) (getMeasuredHeight() / 4 * (1 - val));
bgView2.setLayoutParams(layoutParams2);
LayoutParams layoutParams3 = (LayoutParams) bgView3.getLayoutParams();
layoutParams3.topMargin = (int) (getMeasuredHeight() / 4 * (1.5 - val));
bgView3.setLayoutParams(layoutParams3);
invalidate();
}
});
我发现每次更改子视图的布局框架时,onMeasure()
都会被调用并且值会发生变化。此外,动画根本不起作用。因此,我想知道这是否是创建自定义视图组的标准(右)方法。
非常感谢你!