从对话框到 activity 的按钮位置

Button position from dialog to activity

我一直在尝试从对话框中的按钮获取位置,以便我可以使用它在 activity.

中的该按钮下方放置一个按钮

我尝试了一些方法,但 none 似乎有效

int loc1[] = new int[2];
button.getLocationInWindow(loc1);

int loc2[] = new int[2];
button.getLocationOnScreen(loc2);

我也试过了

button.getX();
button.getY();

该按钮从未放置在对话框中的按钮下方。

(注意我只提到了获取帖子的方法)

有人可以帮助我吗?

谢谢!

Button放置完成后需要等待回调。您使用的代码未返回正确的值,因为该值是在放置 Button 之前返回的。因此,在 height/width 作为 wrap_content 的布局中添加按钮并使用此代码:

layout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
    getViewTreeObserver().removeGlobalOnLayoutListener(this);

    int[] locations = new int[2];
     layout.getLocationOnScreen(locations);
    int x = locations[0];
    int y = locations[1];
}
});

制作布局参数,它们取决于父级,因此您可能应该使用 LinearLayout.LayoutParamsRelativeLayout.LayoutParams(还有其他情况)。

并将 layout_below(button1) 添加到您的 LayoutParams 对象。并将 LayoutParams 设置为您希望显示在第一个按钮 1 下方的新按钮。