2013-01-20 43 views
1

我需要將一個網格放置在RelativeLayout的中心,但我不想僅僅因爲需要將它放在特定的位置上而使用Gravity,使用leftMargin和topMargin。Android:RelativeLayout問題

網格是利用了兩個LinearLayout中的
我嘗試使用此代碼,但我看到在屏幕的左上角的網格:

RelativeLayout fl = new RelativeLayout(this); 

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

    fl.setLayoutParams(flp); 
    fl.setBackgroundResource(R.drawable.background); 

    //Linear Layout to contain grid rows 
    LinearLayout grid_layout = new LinearLayout(this); 

    LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT); 

    llp.leftMargin = (int)Util.convertDpToPixel(200, this); 
    llp.topMargin = (int)Util.convertDpToPixel(200, this); 

    //Set Params 
    grid_layout.setOrientation(LinearLayout.VERTICAL); 
    grid_layout.setId(12); 
    fl.addView(grid_layout, llp); 

    Log.d("Display", "" + grid_layout.getHeight()); 

    //LinearLayout(s) ROWS 
    for (int i = 0; i < 4; i++) 
    { 
     LinearLayout ll = new LinearLayout(this); 

     llp = new LinearLayout.LayoutParams(
       LinearLayout.LayoutParams.WRAP_CONTENT, 
       LinearLayout.LayoutParams.WRAP_CONTENT); 

     ll.setLayoutParams(llp); 
     grid_layout.addView(ll); 

     //Cells 
     for (int j = 0; j < 4; j++) //Creating 4 cell blocks in a row 
     { 
      TextView tv = new TextView(this); 
      tv.setBackgroundResource(R.drawable.cell_shape); 
      tv.setHeight((int)Util.convertDpToPixel(42, this)); 
      tv.setWidth((int)Util.convertDpToPixel(42, this)); 

      ll.addView(tv); 

      grid[i][j] = new CellBlock(grid, i, j, tv, null); //Building the game grid 
     } 
    } 

看來,這兩條線:

llp.leftMargin = (int)Util.convertDpToPixel(200, this); 
llp.topMargin = (int)Util.convertDpToPixel(200, this); 

不起作用!爲什麼它保持將網格放置在左上角?

謝謝

+0

你檢查'Util.convertDpToPixel的返回值(200,這個);'? – ben75

+0

我看不到你的代碼,所以在所有的佈局變化後嘗試fl.invalidate() – AndacAydin

+0

@ ben75:是的,我檢查了返回值,它是正確的.. – Michele

回答

0

你必須使用

RelativeLayout.LayoutParams llp = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT); 
llp.setMargins((int)Util.convertDpToPixel(100, this), (int)Util.convertDpToPixel(200, this), (int)Util.convertDpToPixel(200, this), (int)Util.convertDpToPixel(200, this)); 

,而不是

LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT); 
llp.leftMargin = (int)Util.convertDpToPixel(200, this); 
llp.topMargin = (int)Util.convertDpToPixel(200, this); 

你的RelativeLayout 「grid_layout」

+0

好吧,我想我們已經快到了!現在它可以工作,但電網..不再是電網!我會嘗試改變別的.. – Michele

+0

ook!我只需要調整值!現在它可以工作,非常感謝你! – Michele

+0

我的榮幸:)很高興它解決了 – AndacAydin