2013-05-01 118 views
0

我一直在嘗試在RelativeLayout中設置一個View,但有些奇怪的事情正在發生。當我將LayoutParams設置爲MATCH_PARENT時,視圖不顯示。但是,當我手動設置LayoutParams的大小時,視圖顯示正確。這裏是我的代碼:Android RelativeLayout does not show查看

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

也許問題是,您將容器(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的(我想你想打電話給塞蒂第二次):

rectangle.setY(valueY);