我有一个类,我需要在其中添加一个或多个视图。在此示例中,单个ImageView
.我可以毫无问题地添加视图并使用LayoutParameters
对齐它们,但是当我尝试沿垂直轴将它们对齐或居中时,它们要么粘在顶部,要么根本不出现(它们可能只是在视野之外)。
在构造函数中,我调用一个方法fillView()
,这发生在设置了所有维度等之后。
填充视图()
public void fillView(){
img = new ImageView(context);
rl = new RelativeLayout(context);
img.setImageResource(R.drawable.device_access_not_secure);
rl.addView(img, setCenter());
this.addView(rl, matchParent());
}
匹配父()
public LayoutParams matchParent(){
lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
lp.setMargins(0, 0, 0, 0);
return lp;
}
设置中心()
public LayoutParams setCenter(){
lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); //This puts the view horizontally at the center, but vertically at the top
return lp;
}
同样,添加诸如 ALIGN_RIGHT 或 LOWER 之类的规则可以正常工作,但ALIGN_BOTTOM或CENTER_VERTICALLY则不能。
我尝试使用此方法和LinearLayout
提供setGravity()
,结果相同。
添加RelativeLayout
之前添加ImageView
虽然我仍然不知道为什么我的方法在水平上起作用,而不是垂直工作,但我确实解决了这个问题。发布的方法有效,问题隐藏在onMeasure()
.
我之前通过简单地将它们传递给 setMeasuredDimension()
来设置尺寸。我通过将它们传递给layoutParams()
来解决此问题。我还更改了我用来MeasureSpecs
的整数。
我改变了这个:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(this.getT_Width(), this.getT_Heigth());
this.setMeasuredDimension(desiredHSpec, desiredWSpec);
}
对此:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
final int desiredHSpec = MeasureSpec.makeMeasureSpec(this.getT_heigth(), MeasureSpec.EXACTLY);
final int desiredWSpec = MeasureSpec.makeMeasureSpec(this.getT_width(), MeasureSpec.EXACTLY);
this.getLayoutParams().height = this.getT_heigth();
this.getLayoutParams().width = this.getT_width();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(desiredWSpec);
int height = MeasureSpec.getSize(desiredHSpec);
setMeasuredDimension(width, height);
}
getT_Width()
和getT_Heigth()
是我用来获取在其他地方设置的一些自定义维度的方法。我希望这对某人有所帮助。