2012-12-28 181 views
1

我是Android編程的新手。確定視圖的寬度和高度

我的問題是確定子視圖的寬度和高度的最佳方法是什麼?

我正在寫一個包含鋼琴鍵盤輸入的應用程序。

我有一個自定義視圖,PianoKeyboardView。 我需要知道我的視圖的尺寸才能繪製鍵盤。 如果我將以下代碼的寬度和高度填充到PianoKeyboardView中,我的鋼琴鍵盤畫出OK。

Display display = ((WindowManager) this 
     .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 

    int width = display.getWidht(); 
    int height = display.getHeight(); 

顯然我不想這樣做。

我在Eclipse中創建了一個默認的android應用程序,並選擇了FullScreen選項。爲的onCreate默認代碼爲:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.activity_fullscreen); 

    final View controlsView = findViewById(R.id.fullscreen_content_controls); 
    final View contentView = findViewById(R.id.fullscreen_content); 

當我的默認瀏覽調用的getWidth()和getHeight(),我得到0。

int width = controlsView.getWidth(); 
    int height = controlsView.getHeight(); 
    width = contentView.getWidth(); 
    height = contentView.getHeight(); 

我的PianoKeyboardView的寬度和高度也是0,這就是我的問題。

我activity_fullscreen.xml設置寬度和高度爲所有的意見「match_parent」

<FrameLayout  
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true" > 

    <LinearLayout 
     android:id="@+id/fullscreen_content_controls" 
     style="?buttonBarStyle" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_gravity="bottom|center_horizontal" 
     android:background="@color/black_overlay" 
     android:orientation="horizontal" 
     tools:ignore="UselessParent" > 

     <com.application.piano.PianoKeyboardView 
     android:id="@+id/keyboard_view" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:layout_weight="1" 
     /> 

感謝。

回答

0
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.activity_fullscreen); 

    final View controlsView = findViewById(R.id.fullscreen_content_controls); 
    final View contentView = findViewById(R.id.fullscreen_content); 

    ViewTreeObserver viewTreeObserver = controlsView.getViewTreeObserver(); 
    viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { 
      @Override 
      public boolean onPreDraw() { 
       int width = controlsView.getWidth(); 
       int height = controlsView.getHeight(); 
       return true; 
      } 
    }); 

希望這有助於你.....

+0

非常感謝! 是的,當我在我的PianoKeyboardView中調用onDraw()方法時,寬度和高度已經初始化。所以我只是延遲初始化我的鍵盤,直到第一次調用onDraw。 – user1933620

0

你可以嘗試在此基礎上的東西......(從my answer to a related question複製)。

我用下面的技術 - 從onCreate()發佈可運行的觀點已經被創建時將被執行:

contentView = findViewById(android.R.id.content); 
    contentView.post(new Runnable() 
    { 
     public void run() 
     { 
      contentHeight = contentView.getHeight(); 
     } 
    }); 

此代碼將在主UI線程上運行,onCreate()結束後。在這一點上,視圖已經變大了。

相關問題