0

我一直在尝试在 RelativeLayout 中设置一个视图,但是发生了一些奇怪的事情。当我将 LayoutParams 设置为 MATCH_PARENT 时,视图未显示。但是,当我手动设置 LayoutParams 的大小时,视图会正确显示。这是我的代码:

protected void onCreate(Bundle savedInstanceState) {
...
    RelativeLayout layout = new RelativeLayout(this);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    layout.setLayoutParams(params);

    rectangle = new Rectangle (this);   
    RelativeLayout.LayoutParams rectParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
           LayoutParams.MATCH_PARENT);
    rectangle.setLayoutParams(rectParams); 
    //rectangle.setLayoutParams(new LayoutParams(2000, 1280)); If I do this the Rectangle shows correctly

    rectangle.setX(valueX);
    rectangle.setX(valueY);
    layout.addView(rectangle);
}
class Rectangle extends View {
    Paint paint = new Paint();
    Paint paint2 = new Paint();
    RectF rect = new RectF();
    public Rectangle(Context context) {
        super(context);   
    }

    @Override
    public void onDraw(Canvas canvas) {      
        paint.setColor(Color.rgb(255,20,147));
        rect.set(10, 10, 250, 90);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawRoundRect(rect, 3, 3, paint);

        paint2.setColor(Color.WHITE);
        rect.set(10, 10, 250, 90);
        paint2.setStrokeWidth(5);
        paint2.setStyle(Paint.Style.STROKE);
        canvas.drawRoundRect(rect, 5, 5, paint2);
        canvas.drawLine(210, 39, 230,54, paint2);
        canvas.drawLine(210, 63, 230,52, paint2);
        super.onDraw(canvas);           
    }
}

布局对象在一个滚动内。我一直在尝试更改 LayoutParameters 但没有成功。什么也看不见。有任何想法吗?

4

1 回答 1

0

也许问题是您将容器的布局高度(RelativeLayout)设置为 WRAP_CONTENT,将内容的高度(矩形)设置为 MATCH_PARENT。尝试改变

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

此外,您调用了两次 setX(我想您第二次要调用 setY):

rectangle.setY(valueY);

于 2013-05-01T14:39:39.567 回答