为什么视图的坐标始终为零

时间:2014-05-29 18:11:13

标签: java android rect

我创建了一个简单的示例,以了解如何获取任何给定view的坐标。以下是我的尝试,它们始终显示0.0。知道为什么会这样吗?

代码:

private int [] tv1Location = new int[2];
private int [] tv2Location = new int[2];

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Rect tv1Rect = new Rect();
    Rect tv2Rect = new Rect();

    TableLayout tl = (TableLayout) findViewById(R.id.tableLayout);
    TextView tv1 = (TextView) findViewById(R.id.tv1);
    TextView tv2 = (TextView) findViewById(R.id.tv2);

    tv1.getLocalVisibleRect(tv1Rect);
    tv1.getLocationOnScreen(tv1Location);

    tv2.getLocalVisibleRect(tv1Rect);
    tv2.getLocationOnScreen(tv2Location);


    tv1.setText("xCords: "+tv1.getX()+", yCords: "+tv1.getY());
    tv2.setText("xCords: "+tv2.getX()+", yCords: "+tv2.getY());
    //tv2.setText("xCords: "+tv2Location[0]+", yCords: "+tv2Location[1]);
    //tv1.setText("xCords: "+tv1Location[0]+", yCords: "+tv1Location[1]);
    //tv2.setText("xCords: "+tv2Location[0]+", yCords: "+tv2Location[1]);

更新

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    // TODO Auto-generated method stub
    super.onWindowFocusChanged(hasFocus);

    if (hasFocus) {
            tv1.getLocalVisibleRect(tv1Rect);
            tv1.getLocationOnScreen(tv1Location);

            tv2.getLocalVisibleRect(tv1Rect);
            tv2.getLocationOnScreen(tv2Location);

            //tv1.setText("xCords: "+tv1.getX()+", yCords: "+tv1.getY());
            //tv2.setText("xCords: "+tv2.getX()+", yCords: "+tv2.getY());
            //tv1.setText("xCords: "+tv1Rect.centerX()+", yCords: "+tv1Rect.centerY());
            //tv2.setText("xCords: "+tv2Rect.centerX()+", yCords: "+tv2Rect.centerY());
            //tv1.setText("xCords: "+tv1Location[0]+", yCords: "+tv1Location[1]);
            //tv2.setText("xCords: "+tv2Location[0]+", yCords: "+tv2Location[1]);
        }
    }

3 个答案:

答案 0 :(得分:4)

Views尚未显示。您不应该在onCreate()中放置代码来检查这样的内容,因为可能还没有绘制所有内容。有几种不同的方法可以实现这一目标。最佳位置可能在onWindowFocusChanged

docs say onWindowFocusChanged()

  

这是该活动对用户是否可见的最佳指标

所以你知道Views已经布置在这一点上。您也可以在runnable上发布View或使用。

Here is an answer that uses听众onGlobalLayout,它也可以满足您的需求。

答案 1 :(得分:3)

此时

View既没有测量也没有布局,所以改为这样做:

textView.post(new Runnable() {
        @Override
        public void run() {
            textView.getLocalVisibleRect(rect);
            textView.setText("xCords: "+textView.getX()+", yCords: "+textView.getY());
        }
    });

答案 2 :(得分:0)

一种更好的方法是使用ViewTreeObserver,它会在呈现布局时触发回调,这意味着您可以获取视图的位置。

tv1.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
   tv1.getLocalVisibleRect(tv1Rect);
});

此外,如果不需要,则应删除已安装的侦听器,因为ViewTreeObserver拥有对侦听器对象的强大引用。