0

我有一個空的RelativeLayout。我必須得到佈局的高度和寬度(設置爲匹配父項)。我試圖在網上搜索,但無濟於事。這是我的代碼,你能幫我嗎?當我啓動應用程序時,它會在getCoordinate方法中崩潰。對不起我的英語不好。獲取相對佈局android的度量?

public class MainActivity extends AppCompatActivity { 

Random rand = new Random(); 
int[] coordinate = new int[2]; 

public void getCordinate(final RelativeLayout layout){ 
    layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 

     @Override 
     public void onGlobalLayout() { 
      // Ensure you call it only once : 
      layout.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
      coordinate[0] = layout.getMeasuredWidth();// width must be declare as a field 
      coordinate[1] = layout.getMeasuredHeight();// height must be declare as a fiel 
     } 
    }); 
} 

public void makeButton(RelativeLayout play_area){ 
    int button_x = rand.nextInt(coordinate[0]); 
    int button_y = rand.nextInt(coordinate[1]); 

    Button bomb = new Button(this); 
    bomb.setX((float)button_x); 
    bomb.setY((float)button_y); 
    play_area.addView(bomb); 
} 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    RelativeLayout play_area = (RelativeLayout) findViewById(R.id.play_area); 
    play_area.measure(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); 
    getCordinate(play_area); 

    Log.d("Coordinate", "Xmax: " + coordinate[0] + " Ymax: " + coordinate[1]); 

    //makeButton(play_area); 

} 
} 
+0

如果你描述的異常發生,並可能包括在你的問題堆棧跟蹤這將是有益的。 – ManoDestra

+0

不要在視圖上調用measure()。這是佈局經理的工作。另外,是的,如果有事情崩潰,總是發佈堆棧跟蹤。 –

回答

0

你不應該調用measure()。你可以調用.setLayoutParams(width,height)來設置視圖以匹配父母的寬度/高度。

和簡單的調用.getMeasuredWidth()(或高度)上的觀點應該返回自己的寬度/高度重視

+0

我的佈局必須適應顯示器尺寸。當調整relativelayput時,我必須得到dp中的維數,.getMeasureWidth()每0返回一次 –