在addView()之后获取视图的位置

时间:2015-09-27 10:19:24

标签: android

一切都在标题中。我需要在relativeLayout中的某个点添加视图,但在OnCreate方法中不需要。我想要做的是在用户点击RelativeLayout时添加一个视图,没问题。但是在使用addView方法之后,我需要尽快知道这个视图的位置。目前我正在使用postDelayed,但我需要设置一个高值,以确保在获取视图位置之前显示它。我尝试使用post,但效果不好,所以这就是我使用延迟值的原因。我前段时间也尝试过使用treeObserver,但也许我用错了我不知道因为它不起作用。

编辑: 在这里,我创建了布局参数。

RelativeLayout.LayoutParams laoutparam = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT );
    laoutparam.addRule(RelativeLayout.CENTER_IN_PARENT);

在这里,我创建自定义视图并将layoutparam添加到其中:

Button button = (Button)findViewById(R.id.lol);

    CustView view = new Bubble(getApplicationContext(), "Press this button", button);
    bubble.setLayoutParams(laoutparam);

然后在我的自定义RelativeLayout的构造函数中,我执行addView(view)。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我希望这可以帮助您获取查看位置:https://www.tutorialspoint.com/how-to-get-the-absolute-coordinates-of-a-view-in-android

示例:

int loc[]=new int[2];
yourView.getLocationOnScreen(loc);
int x=loc[0];
int y=loc[1];