新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

Android getLocationOnScreen在滑动时怎样使用

发布时间:2024-07-27 15:28:09

Android getLocationOnScreen在滑动时怎样使用

您可使用ViewTreeObserver来监听View的位置变化,然后在onGlobalLayoutListener中获得View相对屏幕的位置。以下是一个示例代码:

final View view = findViewById(R.id.your_view);

ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int[] location = new int[2];
        view.getLocationOnScreen(location);

        int x = location[0];
        int y = location[1];

        Log.d("TAG", "View location on screen: x=" + x + ", y=" + y);
    }
});

这样,每当View的位置产生变化时,位置信息都会被打印出来。您可以根据需要在这里履行相应的操作。

tiktok粉丝购买:https://www.smmfensi.com/