java - why the coordinates of a view is always Zero -
i created simple example know how can coordinates of given view
. below attempts, , display 0.0
. idea why 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]); } }
you views
not visible yet. shouldn't put code check things in oncreate()
because might not drawn yet. there several different ways accomplish this. best place may in onwindowfocuschanged
the docs onwindowfocuschanged()
this best indicator of whether activity visible user
so know views
laid out @ point. post runnable
on view
s or use.
here answer uses listener ongloballayout work need.
Comments
Post a Comment