为什么getLocationOnScreen()和getLocationInWindow()返回相同的值?

时间:2011-10-09 19:37:17

标签: android android-layout

在Android 2.1模拟器上 在ActivityInstrumentationtestCase2测试类中,
我断言phototButton高于sendButton。

@UiThreadTest public void testViewLocationOnScreen() {
        // Trying to trigger layout
        activity.findViewById(R.id.rootSnap).forceLayout();
        activity.findViewById(R.id.rootSnap).requestLayout();
        activity.photoButton.getRootView().requestLayout();
        activity.photoButton.requestLayout();
        activity.photoButton.invalidate();
        activity.onWindowFocusChanged(true);  

        // Successfull asserts
        assertTrue(activity.hasWindowFocus());
        ViewAsserts.assertOnScreen(activity.photoButton.getRootView(), activity.photoButton);
        ViewAsserts.assertOnScreen(activity.sendButton.getRootView(), activity.sendButton);
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        Assert.assertTrue(activity.photoButton.isShown());
        Assert.assertTrue(activity.sendButton.isShown());

        // Unexpected screen coordinates returned from 
        // getLocationOnScreen() and getLocationInWindow()
        int[] above = new int[2];
        activity.photoButton.getLocationOnScreen(above);
        int[] below = new int[2];
        activity.sendButton.getLocationOnScreen(below);
        log("getLocationOnScreen-above", above);
        log("getLocationOnScreen-below", below);
        // Logs screen coodinates [0, 76] and [0, 178]

        above = new int[2];
        activity.photoButton.getLocationInWindow(above);
        below = new int[2];
        activity.sendButton.getLocationInWindow(below);
        log("getLocationInWindow-above", above);
        log("getLocationInWindow-below", below);
        // Logs window coordinates [0, 76] and [0, 178]
    }

我期待这些方法的不同价值。

为什么getLocationOnScreen()和getLocationInWindow()返回相同的值?

1 个答案:

答案 0 :(得分:4)

我也对此感到困惑,所以我总结了一些调查 here

基本上,窗口位于状态栏下方(关于z顺序而不是y坐标),并且在大多数情况下填充整个屏幕。因此,在正常活动中,您应该期望这些方法返回相同的值。仅在特殊情况下,例如Window实际偏移的对话框,您会看到这些方法返回不同的值。