问题
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;
}
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.
回答1:
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();
来源:https://stackoverflow.com/questions/53034097/how-to-get-a-views-coordinates-in-constraintlayout