我需要將一個網格放置在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);
不起作用!爲什麼它保持將網格放置在左上角?
謝謝
你檢查'Util.convertDpToPixel的返回值(200,這個);'? – ben75
我看不到你的代碼,所以在所有的佈局變化後嘗試fl.invalidate() – AndacAydin
@ ben75:是的,我檢查了返回值,它是正確的.. – Michele