android - 如何在约束布局中获取视图坐标
问题描述
我在使用横向约束布局的垂直链中有七个按钮。
在运行时,我调整按钮的大小,使它们适合应用栏和导航栏之间。我还将水平指南 (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 中的约束设置拉一个数字。我最终试图获得每个按钮的中心坐标。我正在使用上面的宽度(按钮是圆圈),并将向它们添加坐标以计算中心。提前感谢您的帮助。
解决方案
我发现我做错了什么。我使用以下方法来获取中心点。
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();
推荐阅读
- spring - 无需用户登录即可保护 Spring Boot 应用程序
- c# - 有没有办法从一个 IQueryable 复制谓词以添加到 C# 中的新 IQueryable
- recursion - 递归函数中的未绑定值(初学者 OCaml)
- php - 在 Videojs 播放器上将纵向视频显示为 HLS ffmpeg Laravel
- multithreading - IO 线程是否适合基于 Kotlin 构建的 REST (Spring) 服务?
- javascript - 即使“then”返回值响应,useEffect 也返回未定义
- python - 动态定义的实例属性应该如何与类型提示/linting 一起使用?
- c - 关于c中这个特定随机数生成器的问题
- r - 如何获得包含整个数据集的岭回归?
- python - 在 python 中使用机器人查找局部最小值