2010-11-13 60 views
23

Dianne Hackborn在幾個線程中提到,您可以檢測到佈局已調整大小,例如軟鍵盤打開或關閉時。這樣的線程就是這一個...... http://groups.google.com/group/android-developers/browse_thread/thread/d318901586313204/2b2c2c7d4bb04e1b如何檢測佈局大小?

但是,我不明白她的答案:「通過您的視圖層次結構調整所有相應的佈局遍歷和回調。」

有沒有人有進一步的說明或如何檢測這個問題的一些例子?我可以鏈接哪些回調以檢測此問題?

感謝

回答

39

覆蓋onSizeChangedView

+2

我一直希望有一種方法不需要繼承視圖,但它確實按照我想要的方式工作,謝謝。爲了調用視圖的父級活動,我在子類視圖中創建了一個偵聽器,該偵聽器調用它已調整大小的活動。再次感謝。 – cottonBallPaws 2010-11-13 23:29:31

+0

@dacwe如何停止調整大小布局' – PriyankaChauhan 2016-11-15 14:28:07

3

我的解決方案是在佈局/片段的末尾添加一個不可見的小笨視圖(或將其添加爲背景),因此,對佈局大小的任何更改都會觸發該視圖的佈局更改事件,可以通過OnLayoutChangeListener被獲取了:

實施例添加啞視圖佈局的端部:

<View 
    android:id="@+id/theDumbViewId" 
    android:layout_width="1dp" 
    android:layout_height="1dp" 
    /> 

聽事件:

View dumbView = mainView.findViewById(R.id.theDumbViewId); 
    dumbView.addOnLayoutChangeListener(new OnLayoutChangeListener() { 
     @Override 
     public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { 
      // Your code about size changed 
     } 
    }); 
20

一種方法是查看。 addOnLayoutChangeListener。在這種情況下,不需要對視圖進行子類化。但是您確實需要API級別11.並且從邊界(在API中未記錄)正確計算大小有時可能是一個陷阱。這裏有一個正確的示例:

public void onLayoutChange(View v, int left, int top, int right, int bottom, 
    int leftWas, int topWas, int rightWas, int bottomWas) 
{ 
    int widthWas = rightWas - leftWas; // right exclusive, left inclusive 
    if(v.getWidth() != widthWas) 
    { 
     // width has changed 
    } 
    int heightWas = bottomWas - topWas; // bottom exclusive, top inclusive 
    if(v.getHeight() != heightWas) 
    { 
     // height has changed 
    } 
} 

另一種方式(如dacwe答案)是繼承你的看法,並覆蓋onSizeChanged

+0

應該是選定的答案 – 2016-06-27 13:41:55

+0

這真的很有幫助!聰明而美麗:) – 2016-08-23 23:12:02