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

标签 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() 返回相同的值?

最佳答案

我也被这个弄糊涂了,所以我做了一些调查总结一下 here .

基本上,窗口布局在状态栏下方(在 z 轴顺序而非 y 坐标下方),并且在大多数情况下会填满整个屏幕。因此,在正常 Activity 中,您应该期望这些方法返回相同的值。只有在特殊情况下,例如窗口实际偏移的对话框,您才会看到这些方法返回不同的值。

关于android - 为什么 getLocationOnScreen() 和 getLocationInWindow() 返回相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7706042/

相关文章:

android - 如何在 android 中启动股票安装程序应用程序

基于网络运营商的Android UI定制

android - 垂直居中于右侧的 RelativeLayout

android - 垂直显示两个文本字段(在 ListView 中一个在另一个下方)

java - 旧设备中的 PreferenceFragment?

android - 以编程方式在(线性)布局(在 ScrollView 内)中添加 View

java - Android Studio 中的 Recyclerview 错误 - "null object reference"

android - 有什么地方可以让我从 Android 设计指南中获得典型的 XML 样式吗?

android - Build Gradle应用程序 “< ”语法错误启动失败

android - 在android中将可见性设置为GONE后如何恢复布局