获取对话框中视图相对于其父级的位置 [英] Get positions of views in a dialog, relative to their parent
问题描述
我想要做的是,从按钮的边缘到屏幕上的一个点画一条线...
What I want to do is, to draw a line from the edge of a button to a point on the screen...
我为此使用了一个对话框片段...我尝试过的所有函数总是返回 0 点...
I'm using a dialog fragment for this... And all functions I tried always return the 0 point...
我尝试了以下操作:
@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) 画一条线...
and it ALWAYS draws a line from the p(0, 0) to p(0, 30)...
我怎样才能获得一个按钮在屏幕上的位置或相对于它的父视图更可取的位置?我想,他们的布局还没有完成,所以我必须稍后在某个地方画我的线条,但何时何地?
How can I get the position of a button on the screen or preferable relative to it's parent view? I think, they layout is not finished yet, so I have to draw my lines somewhere later, but when and where?
推荐答案
当布局放置子视图时,您需要等待回调.您使用的代码返回 0,因为在放置布局之前返回位置.使用此代码:
You need to wait for the callback when the layout has placed the children views. The code you are using returns 0 because the position is returned before the layout is placed. Use this code:
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];
}
});
这篇关于获取对话框中视图相对于其父级的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!