android listview display all available items without scroll with static header

前端 未结 12 628
一生所求
一生所求 2020-12-02 10:12

I\'m having a little difficulties while trying to get a certain layout to work: I want to have list. List does not have to be scrollable, but should be shown completely. But

12条回答
  •  再見小時候
    2020-12-02 10:31

    I don't have a static header, but using HussoM's post as a clue, here is what I was able to get to work. In my scenario, the height of the items in the list was non-uniform, due to variable text sentences in each of the items, and I am using wrap_content for the height and match_parent for the width.

    public class NonScrollableListView extends ListView {
    
      public NonScrollableListView(Context context) {
          super(context);
      }
    
      public NonScrollableListView(Context context, AttributeSet attrs) {
          super(context, attrs);
      }
    
      public NonScrollableListView(Context context, AttributeSet attrs, int defStyleAttr) {
          super(context, attrs, defStyleAttr);
      }
    
      public NonScrollableListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
          super(context, attrs, defStyleAttr, defStyleRes);
      }
    
      /**
       * Measure the height of all the items in the list and set that to be the height of this
       * view, so it appears as full size and doesn't need to scroll.
       * @param widthMeasureSpec
       * @param heightMeasureSpec
       */
      @Override
      public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
          ListAdapter adapter = this.getAdapter();
          if (adapter == null) {
              // we don't have an adapter yet, so probably initializing.
              super.onMeasure(widthMeasureSpec, heightMeasureSpec);
              return;
          }
    
          int totalHeight = 0;
    
          // compute the height of all the items
          int itemCount = adapter.getCount();
          for (int index=0; index 0) {
              totalHeight += this.getDividerHeight() * Math.max(0, itemCount - 1);
          }
    
          // make it so
          this.setMeasuredDimension(widthMeasureSpec,
                  MeasureSpec.makeMeasureSpec(totalHeight, MeasureSpec.EXACTLY));
      }
    

    }

提交回复
热议问题