我一直在尝试在RelativeLayout中设置一个View,但是发生了一些奇怪的事情。当我将LayoutParams设置为MATCH_PARENT时,视图未显示。但是,当我手动设置LayoutParams的大小时,View会正确显示。这是我的代码:
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但没有成功。没有看到任何东西。有什么想法吗?
答案 0 :(得分:0)
问题可能是您将容器的布局高度(RelativeLayout)设置为WRAP_CONTENT,将内容的高度(Rectangle)设置为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);