如何检测布局调整大小?

cot*_*aws 32 layout user-interface android resize

Dianne Hackborn在几个线程中提到,您可以检测布局何时调整大小,例如,当软键盘打开或关闭时.这样的线程是这个... http://groups.google.com/group/android-developers/browse_thread/thread/d318901586313204/2b2c2c7d4bb04e1b

但是,我不理解她的回答:"通过所有相应的布局遍历和回调调整视图层次结构."

有没有人有进一步的描述或如何检测这个的一些例子?我可以链接哪些回调以便检测到这个?

谢谢

dac*_*cwe 53

视图中覆盖onSizeChanged!

  • 我希望有一个方法不需要对视图进行子类化,但这确实可以正常工作,谢谢.为了调用视图的父活动,我在子类视图中创建了一个监听器,该监听器调用已调整大小的活动.再次感谢. (5认同)

Mic*_*lan 49

一种方式是View.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
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种方式(如dacwe的回答)是对视图进行子类化并覆盖onSizeChanged.

  • 应该是选定的答案 (3认同)

Sli*_*ion 8

使用 Kotlin 扩展:

inline fun View?.onSizeChange(crossinline runnable: () -> Unit) = this?.apply {
    addOnLayoutChangeListener { _, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
        val rect = Rect(left, top, right, bottom)
        val oldRect = Rect(oldLeft, oldTop, oldRight, oldBottom)
        if (rect.width() != oldRect.width() || rect.height() != oldRect.height()) {
            runnable();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

因此使用:

myView.onSizeChange { 
     // Do your thing...
}
Run Code Online (Sandbox Code Playgroud)


Ton*_*ony 5

我的解决方案是在布局/片段的末尾添加一个不可见的微小哑视图(或将其添加为背景),因此布局大小的任何更改都将触发该视图的布局更改事件,该事件可以被捕获通过 OnLayoutChangeListener:

将哑视图添加到布局末尾的示例:

 <View 
    android:id="@+id/theDumbViewId"
    android:layout_width="1dp"
    android:layout_height="1dp"
     />
Run Code Online (Sandbox Code Playgroud)

收听事件:

    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
        }
    });
Run Code Online (Sandbox Code Playgroud)