2014-10-06 43 views
0

返回0,我有這樣的代碼:的getWidth()中的onCreate

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_my); 
    content = (RelativeLayout) findViewById(R.id.content); 
    ball = (Ball) findViewById(R.id.ball); 
    txt = (TextView) findViewById(R.id.textView); 
    txt.setVisibility(View.GONE); 
    Log.d("sizes", String.valueOf(content.getWidth())); 
    ball.setOnTouchListener(this); 

} 

的問題是,在日誌中它說: 「0」。有人可以向我解釋一個活動的生命週期是什麼,你如何衡量一個視圖或者例如如何在開始時直接在一個活動中創建一個彈跳球。謝謝!

回答

2

您必須等待獲取寬度之前繪製佈局。當繪製時,它被測量並且寬度被保存,因此您可以撥打getWidth。您可以添加一個佈局偵聽器來等待視圖被繪製:

final RelativeLayout content = (RelativeLayout) findViewById(R.id.content); 
content.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { 
    @Override 
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { 
     content.removeOnLayoutChangeListener(this); 
     Log.d("sizes", String.valueOf(content.getWidth())); 
    } 
}); 
+0

這是您通常如何操作的方式?如果這是最好的做法比謝謝你! – 2014-10-06 17:16:09

+0

@КристиянКацаров這是我總是這樣做,它總是被證明是可行的。 – Simas 2014-10-06 17:27:19