从对话框到活动的按钮位置

时间:2015-03-27 18:01:19

标签: java android dialog position screen

我一直试图通过对话框中的按钮获取位置,以便我可以使用它在活动中的按钮下方放置一个按钮。

我尝试了一些东西,但它们似乎都没有用

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

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

我也试过

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

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

(我应该注意到我只提到了获得定位的方法)

任何人都可以帮助我吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

您需要在按钮放置后等待回调。您使用的代码未返回正确的值,因为在放置Button之前返回了该值。因此,在高度/宽度为layout_content的布局中添加Button,并使用以下代码:

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];
}
});

答案 1 :(得分:0)

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

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

相关问题