【问题标题】:Retrieve the X & Y coordinates of a button in android?检索android中按钮的X和Y坐标?
【发布时间】:2011-08-26 11:05:47
【问题描述】:

我在 Android 上工作了一段时间,想知道是否可以在 android 中检索按钮的位置。

我的目标是获取 X 和 Y 坐标并将它们打印在 LOGCAT 上。

一些例子来告诉我如何将不胜感激。

谢谢

【问题讨论】:

    标签: android button position


    【解决方案1】:

    当然,您可以获得这些,请确保在尝试获得位置之前至少绘制一次视图。您可以尝试获取 onResume() 中的职位并尝试这些功能

    view.getLocationInWindow()
    or
    view.getLocationOnScreen()
    

    或者如果你需要一些相对于父母的东西,使用

    view.getLeft(), view.getTop()
    

    API 定义的链接:

    【讨论】:

    • getLocationInWindow(int[])getLocationOnScreen(int[]) 有参数。你确定你的想法吗?
    • @hakkikonu 看看我的回答以了解 getLocationInWindow(int[]) 的用法。
    【解决方案2】:

    就像Azlam 说你可以使用View.getLocationInWindow() 来获取坐标x,y

    这是一个例子:

    Button button = (Button) findViewById(R.id.yourButtonId);
    Point point = getPointOfView(button);
    Log.d(TAG, "view point x,y (" + point.x + ", " + point.y + ")");
    
    private Point getPointOfView(View view) {
        int[] location = new int[2];
        view.getLocationInWindow(location);
        return new Point(location[0], location[1]);
    }
    

    奖励 - 获取给定视图的中心点:

    Point centerPoint = getCenterPointOfView(button);
    Log.d(TAG, "view center point x,y (" + centerPoint.x + ", " + centerPoint.y + ")");
    
    private Point getCenterPointOfView(View view) {
        int[] location = new int[2];
        view.getLocationInWindow(location);
        int x = location[0] + view.getWidth() / 2;
        int y = location[1] + view.getHeight() / 2;
        return new Point(x, y);
    }
    

    我希望这个例子仍然对某人有用。

    【讨论】:

      【解决方案3】:
      buttonObj.getX();
      buttonObj.getY();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-02
        • 1970-01-01
        • 2011-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多