Android ListView: Can not center items on start up, due to Null Pointer Exception -
this first ever post here , i'm dumb novice, hope out there can both me , excuse ignorance.
i have listview populated arrayadapter. when either scroll or click, want selected item, or item nearest vertical center, forced exact vertical center of screen. if call listview.setselection(int position) aligns selected position @ top of screen, need use listview.setselectionfromtop(position, offset) instead. find offset, take half of view's height half of listview's height.
so, can vertically center item easy enough, within onitemclick or onscrollstatechanged, following:
int x = listview.getheight(); int y = listview.getchildat(0).getheight(); listview.setselectionfromtop(myposition, x/2 - y/2);
all works fine. problem initial listview setup. want item centered when activity starts, can't because nullpointerexception from:
int y = listview.getchildat(0).getheight();
i understand because listview has not yet rendered, has no children, when call oncreate() or onresume().
so question simply: how can force listview render @ startup can height value need? or, alternatively, there other way center items vertically within listview?
thanks in advance help!
int y = listview.getchildat(0).getheight();
i understand because listview has not yet rendered, has no children, when call oncreate()
or onresume()
.
you should call in onscroll
.
listview.setonscrolllistener(new onscrolllistener() { @override public void onscrollstatechanged(abslistview view, int scrollstate) { } @override public void onscroll(abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) { //write logic here int y = listview.getchildat(0).getheight(); } });
Comments
Post a Comment