Search code examples
javaandroidrect

why the coordinates of a view is always Zero


I created a simple example to know how can I get the coordinates of any given view. Below are my attempts, and they always display 0.0. any idea why that happens?

Code:

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

Updated

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

Solution

  • You Views are not visible yet. You shouldn't put code to check things like this in onCreate() because everything might not be drawn yet. There are several different ways to accomplish this. The best place may be in onWindowFocusChanged

    The docs say onWindowFocusChanged()

    This is the best indicator of whether this activity is visible to the user

    So you know that the Views are laid out at this point. You could also post a runnable on the Views or use.

    Here is an answer that uses the listener onGlobalLayout which could also work for what you need.