我希望我的RelativeLayouts的大小和位置與設備屏幕的大小無關(相對)。例如:RelativeLayout的大小和位置(邊距)
如果設備A具有480的屏幕寬度和800和裝置B的高度具有720和1280高度的屏幕寬度,我的RelativeLayout必須具有,例如,160的寬度和267高度在設備A和240寬度和427高度在設備B。這很簡單,只需獲得屏幕寬度和高度並計算出你想要的百分比。這部分我用下面的代碼和它的工作:
int width = methodToGetScreenWidth();
relativeOneWidth = ((width/100) * 90); // 90% of the screen width.
relativeOneHeight = (int) (relativeOneWidth/1.75f);
relativeTwoWidth = (relativeOneWidth/2);
relativeTwoHeight = (relativeOneHeight/4);
relativeThreeWidth = (relativeOneWidth/4);
relativeThreeHeight = (relativeOneHeight/4);
它在我測試的所有設備工作正常。問題在於這個位置。我嘗試了很多東西來計算邊距,但它並不在每個設備的相同位置(大多數時候它非常接近所需位置,但不是完全相同)。下面是我的嘗試:
relativeOneLeftMargin = ((width - relativeOneWidth)/2); // The screen width - the relativeOne width/2, it should returns the relativeOne left margin, shouldn't it?
relativeOneTopMargin = ((height - relativeOneHeight)/2); // And this, the relativeOne top margin, right?
relativeTwoLeftMargin = (int) (relativeOneLeftMargin * 1.5f);
relativeTwoTopMargin = (int) (relativeOneTopMargin * 0.78f);
relativeThreeLeftMargin = relativeOneTopMargin + relativeOneHeight;
PS:本relativeOne是在屏幕的中間:
relativeOne.addRule(RelativeLayout.CENTER_IN_PARENT);
我也試圖讓利潤這種方式,但它返回0:
relativeOne.getLeft();
relativeOne.getTop();
我真的不知道爲什麼它不在所有設備的相同位置。任何建議?