This is my first post here, and I'm a stupid newbie, so I hope someone out there can help me and excuse my ignorance.
I have a ListView that is populated with an ArrayAdapter. When I either scroll or click, I want the selected item or the item closest to the vertical center to be forced to the vertical center of the screen. If I call listView.setSelection (int position), it aligns the selected position at the top of the screen, so I need to use listView.setSelectionFromTop (position, offset) instead. To find my offset, I take half the height of the view from half the height of the ListView.
So, I can vertically center my element quite easily, within OnItemClick or OnScrollStateChanged, with the following:
int x = listView.getHeight(); int y = listView.getChildAt(0).getHeight(); listView.setSelectionFromTop(myPosition, x/2 - y/2);
All of this works great. My problem is with the initial setup of ListView. I want the element to be centered when the action starts, but I cannot, because I get a NullPointerException:
int y = listView.getChildAt(0).getHeight();
I understand this because the ListView is not yet displayed, so it has no children when I call it from OnCreate () or OnResume ().
So my question is simple: how can I get my ListView to display at startup so that I can get the right height value? Or, alternatively, is there another way to center elements vertically inside a ListView?
Thanks in advance for your help!