【问题标题】:Get positions of views in a dialog, relative to their parent获取对话框中视图相对于其父级的位置
【发布时间】:2013-11-12 14:46:22
【问题描述】:

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

我为此使用了一个对话框片段...而且我尝试的所有函数总是返回 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) 画一条线...

我怎样才能获得屏幕上按钮的位置或相对于它的父视图更可取的位置? 我想,它们的布局还没有完成,所以我必须稍后在某个地方画线,但何时何地?

【问题讨论】:

    标签: android view drawing


    【解决方案1】:

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

    【讨论】:

    • 我已经找到了这个解决方案,并且正在对其进行测试......它可以工作,所以谢谢。在那里,所有方法都可以正常工作......
    • 在onGlobalLayout方法里面,需要添加:YourView.getViewTreeObserver().removeGlobalOnLayoutListener(this)
    猜你喜欢
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 2021-12-15
    • 1970-01-01
    相关资源
    最近更新 更多