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

时间:2013-11-12 14:46:22

标签: android view drawing

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

我正在使用一个对话框片段......我尝试过的所有函数总是返回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 个答案:

答案 0 :(得分:7)

当布局放置子视图时,您需要等待回调。您使用的代码返回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];
}
});