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

Let*_*rIt 0 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]);
Run Code Online (Sandbox Code Playgroud)

更新

@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]);
        }
    }
Run Code Online (Sandbox Code Playgroud)

cod*_*gic 5

Views还不可见。您不应该输入代码来检查此类内容,onCreate()因为所有内容可能尚未绘制。有几种不同的方法可以实现这一点。最好的地方可能是在onWindowFocusChanged

文档 说 onWindowFocusChanged()

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

所以你知道Views现在已经安排好了。runnable您也可以在 s上发布View或使用。

这是一个使用监听器onGlobalLayout 的答案,它也可以满足您的需要。