我一直在尝试在 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 但没有成功。什么也看不见。有任何想法吗?