Get positions of views in a dialog, relative to their parent

℡╲_俬逩灬. 提交于 2019-12-17 17:01:05

问题


What I want to do is, to draw a line from the edge of a button to a point on the screen...

I'm using a dialog fragment for this... And all functions I tried always return the 0 point...

I tried following:

@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;
}

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?


回答1:


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


来源:https://stackoverflow.com/questions/19932253/get-positions-of-views-in-a-dialog-relative-to-their-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!