2013-04-30 30 views
1

我目前有一個創建視圖的活動。該視圖使用其他類(例如創建隨機序列的整數)。一旦創建視圖,我需要運行一個方法(它將顯示使用位圖的序列)。所以一旦用戶點擊「開始遊戲」,這個序列就會顯示出來。在創建視圖後運行方法 - Android

我已經嘗試在通過序列設置內容視圖內部的onCreate方法之後調用該方法不會正確生成(全0)。我已經在myView類的onStart和onFinishInflate中嘗試了這一點。

有沒有一種方法可以在一切都充氣和初始化後運行此方法?因此,在用戶點擊「開始遊戲」並且視圖改變之後,該方法需要運行。

感謝您的期待。

編輯:嘗試失敗。

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    this.gameView = new GameView(getApplicationContext(), getCellSource(getApplicationContext())); 
    setContentView(this.gameView); 
    // this.gameView.displaySequence(this.gameView.gameEngine.getGenSequence()); Need this to run once view is displayed. 
} 
+0

你能否提供一些你寫的代碼? – 2013-04-30 10:25:47

回答

7

嘗試使用ViewTreeObserver如下:

final View yourView = View.inflate(....); 
    ViewTreeObserver observer = yourView .getViewTreeObserver(); 

    observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 

     @Override 
     public void onGlobalLayout() { 
      yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
      // Do what you need with yourView here... 

     } 
    }); 

注意,函數removeGlobalOnLayoutListener(這)是在一些SDK版本不同。

+0

這是添加在活動或視圖? – Waddas 2013-04-30 10:45:46

+0

在佈局中綁定活動中的視圖之後 – 2013-04-30 10:46:41