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