Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ListView: Detect if ListView data fits on screen without scrolling [duplicate]

Possible Duplicate:
Android: using notifyDataSetChanged and getLastVisiblePosition - when the listView is actually updated?

I have a simple ListView with only a few entries. Depending on the device size and orientation, the ListView needs to scroll or not.

I have also a picture on the screen, which is not really necessary. I would like to remove the picture if there is not enough space for the ListView without scrolling.

When I fill my ListView in the onCreate of the activity, the getLastVisiblePosition() is not yet valid, it returns -1. Thus I can not compare last visible item to list count.

int lastVisiblePos = listView.getLastVisiblePosition(); // returns -1

(If I click on a button later to recheck, the value is correct.)

Using the onScrollingListener is too late, as the picture should not be shown in the first place.

I am developing on API level 10.

Any suggestions?

like image 430
Gunnar Bernstein Avatar asked Nov 26 '12 20:11

Gunnar Bernstein


1 Answers

Compare getLastVisiblePosition() with getCount() in a Runnable to see if the entire ListView fits on the screen as soon as it has been drawn. You should also check to see if the last visible row fits entirely on the screen.

Create the Runnable:

ListView listView;
Runnable fitsOnScreen = new Runnable() {
    @Override
    public void run() {
        int last = listView.getLastVisiblePosition();
        if(last == listView.getCount() - 1 && listView.getChildAt(last).getBottom() <= listView.getHeight()) {
            // It fits!
        }
        else {
            // It doesn't fit...
        }
    }
};

In onCreate() queue your Runnable in the ListView's Handler:

listView.post(fitsOnScreen);
like image 145
Sam Avatar answered Sep 28 '22 04:09

Sam