0

I have a listView in my screen. This listView fills 2/3 of my screen (so its height varies on different devices). I have - lets say 50 items in my array list - but I need to put X number of items in it which is visible to the user (e.g on small screen 3, on normal screen 5, on tablet 8).

So the way I'm doing is getting the height of listView in PX, then get its DP size and since I know the height of each row is 60dp then divide height of listViwe in DP format to height of row (which 60dp). So it returns number of items that will be visible to the user and I pass this number to getCount() method of my adapter to populate this amount of items.

This is my code, I have an observer that will be assigned some where in onCreate() method like this this.mListView.getViewTreeObserver().addOnGlobalLayoutListener(mListViewGlobalListener);

        ViewTreeObserver.OnGlobalLayoutListener mListViewGlobalListener = new ViewTreeObserver.OnGlobalLayoutListener()
        {
            @Override
            public void onGlobalLayout()
            {
                removeListViewListener();

                if (mListView == null || mAdapter == null)
                {
                    return;
                }

                int heightInPx = mListView.getHeight();
                int heightInDp = pixelsToDp(heightInPx, getResources().getDisplayMetrics());
                int maxDisplayDriver = heightInDp / 60;
                mAdapter.setMaxDisplayDrivers(maxDisplayDriver);
                Logger.error("TEST", "heightInPx:" + heightInPx + ", heightInDp:" + heightInDp + ", maxDisplayDriver:" + maxDisplayDriver);
            }
        };

    public static int pixelsToDp(int px, DisplayMetrics metrics)
    {
          return (int) (px / metrics.density);
    }

Now when I run the app I have following log: E/TEST: heightInPx:96, heightInDp:32, maxDisplayDriver:0

I believe the height is wrong because I can put at least 4 items in my screen that will be 240dp, while the log shows something else.

4

1 回答 1

1

You can get the height of listview this way because a listview can have n number of childs and getHeight() returns the actual height not the height of currently visible portion. So for listview and other similar view it doesn't return height as even system doesn't know because all childitems are not yet rendered.

So as suggested by other geeks as well, you need to calculate the height of item + margin+padding (if any) and then multiply it by number of child(how do you know this? read ahead). Now number of child would be different in different screen size. So you need to put a counter inside getView to check how many times its getting called onCreate to get to know the number of childitem

于 2016-01-16T07:51:34.490 回答