我有觀點認爲,由xml中的android:layout_centerHorizontal =「true」。我如何獲取左邊的邊緣,以便我可以將其他視圖與它對齊?如何在android中獲取居中視圖的左邊距?
我試着在居中視圖上使用getLayoutParams,但它沒有奏效。它似乎報告左邊0. 0.
我也試着用(screenWidth-view width)/ 2來計算leftMargin,但是它給出了比預期略高的值。更具體地說,這是我的代碼:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int screenWidth = size.x;
int screenHeight = size.y;
TextView button1 = (TextView) findViewById(R.id.button1);
RelativeLayout.LayoutParams params=(RelativeLayout.LayoutParams)
button1.getLayoutParams();
params.height=102;
params.width=114;
params.topMargin =0;
button1.setLayoutParams(params);
params=(RelativeLayout.LayoutParams) button1.getLayoutParams();
int leftMargin = params.leftMargin;
TextView button2 = (TextView) findViewById(R.id.button2);
params=(RelativeLayout.LayoutParams) button2.getLayoutParams();
params.height=102;
params.width=114;
params.leftMargin =leftMargin;
params.topMargin =102;
button2.setLayoutParams(params);
TextView button3 = (TextView) findViewById(R.id.button3);
params=(RelativeLayout.LayoutParams) button3.getLayoutParams();
params.height=102;
params.width=114;
params.leftMargin =(screenWidth-114)/2;
params.topMargin =204;
button3.setLayoutParams(params);
Button1以xml爲中心。 Button2是左對齊的,不居中。 Button3或多或少居中,但稍向右。
所以,
1)我如何才能在XML爲中心的視圖左側的保證金?
2)我該如何在代碼中精確定位視圖? getDefaultDisplay報告的寬度是否比實際屏幕寬度高?
你試過' android:layout_alignLeft'或'android:layout_alignStart'?您可以通過指定其ID來使用此視圖與您希望與居中視圖對齊的視圖。 – razzledazzle