如何将动态高度设置为列表视图

时间:2016-08-17 05:24:14

标签: android listview checkbox toggle

大家好我需要帮助才能将动态高度设置为列表视图。

在我的任务中有一个listView里面的滚动视图,所以我需要将动态高度设置为列表视图,以使任务在滚动视图中完成。

我正在使用how to change the height of the ListView dynamically in andrtoid中的以下代码。 这段代码运行良好,但问题在于这个代码使得duble高度列出视图。

如果列表视图中只有 3项,则会使listview高度等于 6项

我想知道如何解决它。

这是我的代码。

 public class Utility {
       public static void setListViewHeightBasedOnChildren(ListView listView) {
           ListAdapter listAdapter = listView.getAdapter();
           if (listAdapter == null) {
               // pre-condition
               return;
           }

           int totalHeight = 0;
           int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.AT_MOST);
           for (int i = 0; i < listAdapter.getCount(); i++) {
               View listItem = listAdapter.getView(i, null, listView);
               listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
               totalHeight += listItem.getMeasuredHeight();
           }

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

我在listview活动中使用它喜欢:

SimpleAdapter simpleadapter = new SimpleAdapter(getApplicationContext(), alist, R.layout.fragmentsrow, getItems, setItems);

        ListViewWelcomePage.setAdapter(simpleadapter);

        Utility.setListViewHeightBasedOnChildren(ListViewWelcomePage);

1 个答案:

答案 0 :(得分:0)

您可以使用ExpandableHeightListView而不是普通的ListView。 请参阅此github库https://github.com/PaoloRotolo/ExpandableHeightListView

相关问题