Chris Banes Chris Banes - 1 year ago 64
Android Question

ListView - Set Minimum Height so that it always allows Scrolling

I'm currently implementing Pull To Refresh functionality in Android. Now I have it working by creating a custom ListView using Header Views above the list items. In essence: when the top header view is in view, a refresh is started via a listener.

On starting the ListView, it automatically scrolls itself below the HeaderViews, hiding them until the user scrolls down. This works great when the the height of List Items exceeds the height the ListView itself (therefore there is scrolling), but when the Height of the Children is less than the height of the ListView, there is no scrolling and HeaderViews are forced to be shown.

Basically what I'm after is a way to force the Scrolling region of the ListView to be at least the height of the ListView + height of my HeaderViews. I've already got the height of my HeaderViews, I just can't find a way of getting the actual height of the ListView (i.e. when fill_parent is used) and a way of setting the minimum scrolling height. Any ideas?

This will be released on GitHub after I'm finished it, and works on Android 1.5+.

Answer Source

I fixed this myself by by adding a footerView to a large enough size:

final int numberHeaderViewsForPullToRefresh = 2;

protected void onSizeChanged(int w, final int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

    if (this.getCount() > numberHeaderViewsForPullToRefresh) {

        // This is from Droid-Fu. Converts dip to px
        final int size = DisplaySupport.dipToPx(getContext(), 60);
        int childViewHeight = (this.getCount() - numberHeaderViewsForPullToRefresh) * size;

        Utils.writeLog("Child Views Height: " + childViewHeight);

        if (childViewHeight < h) {
            footerPad.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, h - childViewHeight));
            this.addFooterView(footerPad, null, false);