D T
D T

Reputation: 3746

Why get Height of ListView not correct?

This is my function calculator Height of ListView:

 fun setListViewHeightBasedOnChildren(listView: ListView) {
        val listAdapter = listView.getAdapter() ?: return

        val desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.UNSPECIFIED)
        var totalHeight = 0
        var view: View? = null
        for (i in 0 until listAdapter.getCount()) {
            view = listAdapter.getView(i, view, listView)
            if (i == 0)
                view!!.layoutParams = ViewGroup.LayoutParams(desiredWidth, LinearLayout.LayoutParams.WRAP_CONTENT)

            view!!.measure(desiredWidth, MeasureSpec.UNSPECIFIED)
            totalHeight += view.measuredHeight 
        }
        val params = listView.getLayoutParams()
        params.height = totalHeight + listView.getDividerHeight()  * (listAdapter.getCount() - 1)
        listView.setLayoutParams(params)
    }

And call display all items:

 setListViewHeightBasedOnChildren(listView)

Result: last row not display ok: enter image description here

Why get Height of ListView not correct?

Upvotes: 0

Views: 137

Answers (1)

Hitesh Sarsava
Hitesh Sarsava

Reputation: 680

check below answer :

ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.AT_MOST);
        Log.d("list", "" + listAdapter.getCount());

        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);

            if (listItem != null) {
                // This next line is needed before you call measure or else you won't get measured height at all. The listitem needs to be drawn first to know the height.
                listItem.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
                listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
                totalHeight += listItem.getMeasuredHeight();

                Log.d("total height", "" + totalHeight);

            }
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));

        Log.d("params height", "" + params.height);

        listView.setLayoutParams(params);
        listView.requestLayout();

may be you forgot total top and bottom padding and setting params to listview item like above code.

Upvotes: 1

Related Questions