简体   繁体   English

Android RelativeLayout不显示视图

[英]Android RelativeLayout doesnt show View

I've been trying to set a View inside a RelativeLayout but something strange is happeing. 我一直在尝试在RelativeLayout内设置一个View,但是有些奇怪。 When i set the LayoutParams to MATCH_PARENT the view is not showing. 当我将LayoutParams设置为MATCH_PARENT时,视图未显示。 However when I set the size of the LayoutParams manually the View is showing correcly. 但是,当我手动设置LayoutParams的大小时,视图将正确显示。 Here is my code: 这是我的代码:

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

The layout object is inside a scroll . 布局对象位于滚动条内部。 I've been trying to change the LayoutParameters but no success. 我一直在尝试更改LayoutParameters,但没有成功。 Nothing is seen. 一无所获。 Any ideas? 有任何想法吗?

Maybe the problem is that you set the layout height of the container (the RelativeLayout) as WRAP_CONTENT, and the height of the content (the Rectangle) as MATCH_PARENT. 可能的问题是,您将容器的布局高度(RelativeLayout)设置为WRAP_CONTENT,而内容的高度(矩形)则设置为MATCH_PARENT。 Try to change 尝试改变

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

with

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

Furthermore, you call two times setX (I suppose the second time you want to call setY): 此外,您两次调用setX(我想第二次您要调用setY):

rectangle.setY(valueY);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM