首页 > 解决方案 > 如何在约束布局中获取视图坐标

问题描述

我在使用横向约束布局的垂直链中有七个按钮。
在运行时,我调整按钮的大小,使它们适合应用栏和导航栏之间。我还将水平指南 (guide1) 放置在应用栏的底部,另一个指南 2 位于导航栏的顶部。我已将顶部按钮(1 或 7)限制为指南 1,将底部按钮(7 个,共 7 个)限制为指南 2。

在同一运行时间内,我可以通过调用以下方法来拉出按钮的新宽度。

int  getwidth(Button btn){
    ConstraintLayout.LayoutParams newLayoutParams = (ConstraintLayout.LayoutParams) btn.getLayoutParams();
    int btnwidth=newLayoutParams.width;
     return btnwidth;
}

在如上所述调整大小之后,我还试图获取每个按钮的屏幕坐标。我试过使用 btn.getTop(); 但结果返回不正确。
我怀疑它是根据我的 xml 中的约束设置拉一个数字。我最终试图获得每个按钮的中心坐标。我正在使用上面的宽度(按钮是圆圈),并将向它们添加坐标以计算中心。提前感谢您的帮助。

标签: androidandroid-constraintlayout

解决方案


我发现我做错了什么。我使用以下方法来获取中心点。

 final int lineStartX = ((ConstraintLayout.LayoutParams) vBtn1.getLayoutParams()).leftMargin + (vBtn1.getMeasuredWidth() / 2)+vBtn1.getLeft();
            final int lineStartY = ((ConstraintLayout.LayoutParams) vBtn1.getLayoutParams()).topMargin + (vBtn1.getMeasuredHeight() / 2)+vBtn1.getTop();
            final int lineEndX = ((ConstraintLayout.LayoutParams) vBtn2.getLayoutParams()).leftMargin + (vBtn2.getMeasuredWidth() / 2)+vBtn2.getLeft();
            final int lineEndY = ((ConstraintLayout.LayoutParams) vBtn2.getLayoutParams()).topMargin + (vBtn2.getMeasuredHeight() / 2)+vBtn2.getTop();

推荐阅读