视图不会垂直对齐或居中

时间:2012-12-17 11:25:53

标签: android android-layout

我有一个类,我需要添加一个或多个视图。在此示例中,单个ImageView。 我可以毫无问题地添加视图并使用LayoutParameters对齐它们,但是当我尝试将它们沿着垂直轴对齐或居中时,它们要么粘在顶部,要么根本不显示(它们可能只是在视野内)。
在构造函数中,我调用了一个方法fillView(),该方法在设置了所有维度之后发生。

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());
}

matchParent()

public LayoutParams matchParent(){
    lp = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    lp.setMargins(0, 0, 0, 0);
    return lp;
}

setCenter()

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或BELOW等规则可以正常工作,但ALIGN_BOTTOM或CENTER_VERTICALLY不会。

我尝试使用此方法和setGravity()一个LinearLayout优惠,结果相同。

2 个答案:

答案 0 :(得分:0)

您在添加ImageView

之前添加了RelativeLayout

答案 1 :(得分:0)

虽然我仍然不知道为什么我的方法水平工作,但不垂直工作,我确实解决了问题。发布的方法有效,问题隐藏在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()是我用来获取我在别处设置的一些自定义维度的方法。 我希望这有助于某人。