如何在constraintlayout中获取视图坐标 [英] how to get a views coordinates in constraintlayout

查看:128
本文介绍了如何在constraintlayout中获取视图坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've seven buttons in a vertical chain using a landscape constraint layout.
At run time I size my buttons so they fit between the appbar and navigation bar. I also position a horizontal guide (guide1) to begin at the bottom of the app bar and another one, guide2, at the top of the navbar. I've constrained the top button (1 or 7) to guide 1 and the bottom button (7 of 7) to guide2.

在相同的运行时间中,我可以通过调用以下方法来拉动按钮的新宽度.

During the same run time I'm able to pull the new width of the button by calling the following method.

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

在如上所述调整按钮大小之后,我还尝试获取每个按钮的屏幕坐标.我试过使用btn.getTop();但结果返回错误.
我怀疑它基于我的xml中的约束设置提取了一个数字.我最终试图获取每个按钮的中心坐标.我从上方使用宽度(按钮为圆形),并将其添加到坐标中以计算中心.预先感谢您的帮助.

I'm also trying to get the screen coordinates of each of the buttons, after I've sized them as described above. I've tried using btn.getTop(); but the results are coming back incorrectly.
I suspect it's pulling a number based on the constraint settings in my xml. I'm ultimately trying to get the center coordinates of each of the buttons. I'm using the width from above (the buttons are circles) and will add to them the coordinates to calculate the centers. Thanks in advance for any help.

推荐答案

我发现自己做错了.我使用以下方法来获取中心点.

I found what I was doing incorrectly. I used the following to get the center points.

 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();

这篇关于如何在constraintlayout中获取视图坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆