0

我有一个需要添加一个或多个视图的类。在此示例中,单个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 或 BELOW 之类的规则也可以正常工作,但 ALIGN_BOTTOM 或 CENTER_VERTICALLY 则不行。

我尝试同时使用此方法和setGravity()aLinearLayout报价,结果相同。

4

2 回答 2

0

您在添加ImageView之前添加RelativeLayout

于 2012-12-17T11:38:01.377 回答
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()是我用来获取我在其他地方设置的一些自定义尺寸的方法。我希望这对某人有所帮助。

于 2013-01-02T10:54:33.497 回答