2010-11-13 28 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