在视图中第一次调用getDecorView。如何知道视图是否被锁定?

时间:2015-10-02 18:50:30

标签: android android-activity android-windowmanager

以下是Window.getDecorView()的文档 http://developer.android.com/reference/android/view/Window.html#getDecorView()

据此,当首次调用API时,各种窗口特征处于锁定模式。哪个好。但有没有办法检查窗口中的当前视图是否处于锁定状态? 我正在尝试调用这样的方法:

private void replaceView() {
    Window window = getActivity().getWindow();
    WindowManager wm = getActivity().getWindowManager();
    wm.removeViewImmediate(window.getDecorView());
    wm.addView(window.getDecorView(), window.getAttributes());
}

现在在某些用例(如方向更改)中,当第一次调用上述方法时,我会崩溃。

java.lang.IllegalArgumentException: View=com.android.internal.policy.impl.PhoneWindow$DecorView{eebbc2d V.ED.... R.....ID 0,0-0,0} not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:396)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:322)
at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:116)
at com.airwatch.inbox2015.ui.email.MessageComposeFragment.replaceView(MessageComposeFragment.java:619)

有可能通过某种方式知道这里我第一次调用getDecorView()所以removeViewImmediate()API可能不起作用,因此我可以避免调用该API吗?

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:2)

使用 peekDecorView 来发现锁定状态。它将“检索当前的装饰视图,但前提是它已经被创建”。例如,在您的活动中:

View decorView = getWindow().peekDecorView();
if( decorView == null )
{
    // Not created yet, maybe because setContentView was not called.
    // Calling getDecorView at this point forces creation, but also
    // "locks in various window characteristics", maybe prematurely.
    // You probably want to avoid that.
}
else
{
    // Window characteristics are locked in, and decorView is safely
    // ready to use.
}

使用peekDecorView可以避免getDecorView的副作用。如果这种方法无法解决您的崩溃问题,那么希望它能让您更接近解决方案。