예제 #1
0
    /** 设置ListView的高度(动态的) TODO delete */
    private void setListViewHeightBasedOnChildren(ListView listView) {

      ListAdapter listAdapter = listView.getAdapter();

      if (listAdapter == null) {
        return;
      }

      int totalHeight = 0;
      if (listAdapter.getCount() > showItemCount) {
        for (int i = 0; i < showItemCount; i++) {
          View listItem = listAdapter.getView(i, null, listView);
          listItem.measure(0, 0);
          totalHeight += listItem.getMeasuredHeight();
        }
      } else {
        for (int i = 0; i < listAdapter.getCount(); i++) {
          View listItem = listAdapter.getView(i, null, listView);
          listItem.measure(0, 0);
          totalHeight += listItem.getMeasuredHeight();
        }
      }

      ViewGroup.LayoutParams params = listView.getLayoutParams();
      int count = 7;
      if (listAdapter.getCount() < 8) {
        count = listAdapter.getCount();
      }
      if (totalHeight > 600) {
        totalHeight = 600;
      }
      params.height = totalHeight + (listView.getDividerHeight() * (count - 1));
      // ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10); // 可删除

      listView.setLayoutParams(params);
    }