2014-01-08 78 views
0

我希望我的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(); 

我真的不知道爲什麼它不在所有設備的相同位置。任何建議?

回答

1

首先,在不同設備中使用定位時,建議使用DP(設備相關點)。你可以看到如何在http://developer.android.com/guide/practices/screens_support.html

當您使用使用它們:

relativeOne.getLeft(); 
relativeOne.getTop(); 

你總是會得到0,因爲,此刻的你做這樣的判斷,Android的沒有繪製完成佈局的父,因此它沒有關於其相對定位的信息。如果你想訪問這些信息,你必須在繪圖後打電話。做到這一點的一種方法是使用類視圖的方法post:

parent.post(new Runnable() { 
      @Override 
      public void run() { 
       relativeOne.getLeft(); 
       relativeOne.getTop(); 
      } 
     }); 

通過這種方式,您可以在繪製佈局後執行調用。

0

我改變了這種代碼:

relativeTwoLeftMargin = (int) (relativeOneLeftMargin * 1.5f); 
relativeTwoTopMargin = (int) (relativeOneTopMargin * 0.78f); 

這一個:

relativeTwoLeftMargin = Math.round(relativeOneLeftMargin * 1.5f); 
relativeTwoTopMargin = Math.round(relativeOneTopMargin * 0.78f); 

現在,它的工作。我猜int轉換沒有返回完全的值。