Reputation: 11050
I have a ListView
which contains an ArrayAdapter
which contains items for each hour of the day, and I need it to place the item which contains the current hour in the center of the visible region of the ListView.
I've tried setSelection
, but it will place the item on the top instead of the center.
Is there any method to do it without calculating layout heights and such?
Right now I'm using this method, because I know the items are 40dip tall, but they won't always be 40dip tall.
private void centerListView() {
final Calendar c = Calendar.getInstance();
final int hour = c.get(Calendar.HOUR_OF_DAY);
final int listViewProgrammerPixels = listViewProgrammer.getHeight();
final int itemPixels = (int) (40 * getResources().getDisplayMetrics().density + 0.5f);
final int pixelsFromTop = (listViewProgrammerPixels - itemPixels) / 2;
listViewProgrammer.setSelectionFromTop(hour, pixelsFromTop);
}
Upvotes: 3
Views: 1457
Reputation: 627
I have done this using this logic first you have to get height of ListView and the height of View in adapter getView method then write this code in your click event .
int offset = ((listViewheight / 2) - (viewHeight / 2));
mListView.smoothScrollToPositionFromTop(position,Math.abs(offset));
Hope this will work for you.
Upvotes: 1
Reputation: 22493
Use this property item_layout.setGravity(Gravity.CENTER);
Upvotes: 0