【问题标题】:Get location of view on screen in a ViewPager在 ViewPager 中获取屏幕上视图的位置
【发布时间】:2021-09-27 16:51:09
【问题描述】:

要获取视图的位置/位置,这是非常标准的:

int[] location = new int[2];
childView.getLocationOnScreen(location);
int x = location[0];
int y = location[1];

但是,如果我在 ViewPager 的第 2 位,并且我尝试在屏幕上获取视图的位置,则此计算将关闭。在 ViewPager 的第一页上,它给出了 x 轴的正确位置 15。但是,在第 2 页上,它为 x 轴提供了 1095。我注意到它似乎在 x 值上增加了 1080,因为设备的分辨率宽度为 1080px。如果我尝试在 ViewPager 的第 3 页上获取同一视图的位置,它会给出 2175 (1080 + 1080 + 15)。

那么如何在不添加额外像素的情况下通过 ViewPager 获取屏幕上视图的位置?

谢谢!

【问题讨论】:

    标签: android android-viewpager


    【解决方案1】:

    PagerAdapter 中,您可以覆盖instantiateItem。您可以接收 int position 作为参数。

    所以将position 保留在某处,然后与视图的宽度(viewWidth)结合:

    x = location[0] - viewWidth * position;
    

    【讨论】:

    • 有没有其他方法可以在屏幕上获取视图的位置而无需添加宽度/乘以位置?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    相关资源
    最近更新 更多