Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

android - 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...

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...