Gridview height gets cut

后端 未结 6 1541
刺人心
刺人心 2020-11-22 17:26

I\'m trying to display 8 items inside a gridview. Sadly, the gridview height is always too little, so that it only shows the first row, and a little part of the second.

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 17:47

    After (too much) research, I stumbled on the excellent answer of Neil Traft.

    Adapting his work for the GridView has been dead easy.

    ExpandableHeightGridView.java:

    package com.example;
    public class ExpandableHeightGridView extends GridView
    {
    
        boolean expanded = false;
    
        public ExpandableHeightGridView(Context context)
        {
            super(context);
        }
    
        public ExpandableHeightGridView(Context context, AttributeSet attrs)
        {
            super(context, attrs);
        }
    
        public ExpandableHeightGridView(Context context, AttributeSet attrs,
                int defStyle)
        {
            super(context, attrs, defStyle);
        }
    
        public boolean isExpanded()
        {
            return expanded;
        }
    
        @Override
        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            // HACK! TAKE THAT ANDROID!
            if (isExpanded())
            {
                // Calculate entire height by providing a very large height hint.
                // View.MEASURED_SIZE_MASK represents the largest height possible.
                int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK,
                        MeasureSpec.AT_MOST);
                super.onMeasure(widthMeasureSpec, expandSpec);
    
                ViewGroup.LayoutParams params = getLayoutParams();
                params.height = getMeasuredHeight();
            }
            else
            {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }
        }
    
        public void setExpanded(boolean expanded)
        {
            this.expanded = expanded;
        }
    }
    

    Include it in your layout like this:

    
    

    Lastly you just need to ask it to expand:

    mAppsGrid = (ExpandableHeightGridView) findViewById(R.id.myId);
    mAppsGrid.setExpanded(true);
    

提交回复
热议问题