获取对话框中视图相对于其父视图的位置。

4

我希望做的是,从按钮边缘画一条线到屏幕上的某个点...

我正在使用对话框片段进行此操作...但我尝试过的所有函数都返回0点...

我尝试了以下方法:

@Override
protected Dialog createDialog(Bundle savedInstanceState, FragmentActivity activity)
{
    Dialog d = builder.create();

    View v = LayoutInflater.from(activity).inflate(R.layout.dialog, null);
    builder.setView(v);

    // custom view by my which draws simple lines between points...
    LineDrawView ldv = new LineDrawView(getActivity());
    ldv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    ((RelativeLayout)v).addView(ldv);
    Dialog d = builder.create();

    button = ((Button) v.findViewById(R.id.button));
    int[] pos = new int[2];
    button.getLocationInWindow(pos);

//           tried following ways, all always return p(0, 0)
//           button.getLocationInWindow(pos);
//           Debugger.d("x: " + pos[0] + ", y: " + pos[1], "POS");

//           button.getLocationOnScreen(pos);
//           Debugger.d("x: " + pos[0] + ", y: " + pos[1], "POS");

//           float x = button.getLeft();
//           float y = button.getTop();
//           Debugger.d("x: " + x + ", y: " + y, "POS");


    ldv.addLine(new Point(pos[0], pos[1]), new Point(pos[0] + 30, pos[1]), Color.RED);
    ldv.invalidate();
    return d;
}

它始终从p(0, 0)到p(0, 30)绘制一条线...

如何获取屏幕上按钮的位置或相对于其父视图的位置?我认为,布局尚未完成,因此我必须稍后在某个地方绘制我的线条,但是在何时和何处呢?

1个回答

6

在布局放置子视图后,您需要等待回调。因为您正在使用的代码返回0,这是因为位置是在布局放置之前返回的。请使用以下代码:

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

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

我找到了这个解决方案并进行了测试...它有效,所以谢谢。在其中,所有的方法都正常工作... - prom85
在 onGlobalLayout 方法内,你需要添加:YourView.getViewTreeObserver().removeGlobalOnLayoutListener(this)。 - maxwellnewage

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接