how to calculate listview height of different height listitem in android?

若如初见. 提交于 2019-12-12 01:57:45

问题


This code is work but the issue is in ListView each item of ListView is diff so last item of ListView is not display because big height ListView item get this space .

here is code:

public static void setListViewHeightBasedOnChildren(ListView listView,DownloadAdapter adapter,LinearLayout layDownloads) {

ListAdapter mAdapter = adapter;

    int totalHeight = 0,h=0;
    int listWidth=listView.getMeasuredWidth();

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

    mView.measure(
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        h=mView.getMeasuredHeight();
        totalHeight += mView.getMeasuredHeight();

    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight
            + (listView.getDividerHeight() * (mAdapter.getCount() - 1))+h;
    listView.setLayoutParams(params);
    listView.requestLayout();

}

Here is screen

please help me how to get height of listview of each cell and to to calculate heght of listview? Thanks in advance..


回答1:


your function replace by

public static void getTotalHeightofListView(ListView listView) {

    ListAdapter mAdapter = listView.getAdapter();

    int totalHeight = 0;
    int listWidth = listView.getMeasuredWidth();

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

        mView.measure(MeasureSpec.makeMeasureSpec(listWidth, MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

        totalHeight += mView.getMeasuredHeight();
        Log.w("HEIGHT" + i, String.valueOf(totalHeight));

    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight
            + (listView.getDividerHeight() * (mAdapter.getCount() - 1));
    listView.setLayoutParams(params);
    listView.requestLayout();
}



回答2:


ANS use this

mView.measure(MeasureSpec.makeMeasureSpec(listWidth, MeasureSpec.EXACTLY),MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

on your code

mView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));



来源:https://stackoverflow.com/questions/25197133/how-to-calculate-listview-height-of-different-height-listitem-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!