How to assign wrap_content as height to dynamically loaded gridview

前端 未结 5 2109
-上瘾入骨i
-上瘾入骨i 2021-01-14 08:31

I am loading gridview dynamically with buttons. So for that I am using scrollview, But if i assign wrap_content as height to gridview all the buttons are not displayed. I do

5条回答
  •  萌比男神i
    2021-01-14 09:05

    You need to create a new class for example

    public class WrappingGridView extends GridView {
    
    public WrappingGridView(Context context) {
        super(context);
    }
    
    public WrappingGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    
    public WrappingGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightSpec = heightMeasureSpec;
        if (getLayoutParams().height == LayoutParams.WRAP_CONTENT) {
            // The great Android "hackatlon", the love, the magic.
            // The two leftmost bits in the height measure spec have
            // a special meaning, hence we can't use them to describe height.
            heightSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        }
        super.onMeasure(widthMeasureSpec, heightSpec);
    }
    
    }
    

    also you need to change in your XML

    
    

    and finally in your java class you need to chance the object GridView to WrappingGridView

提交回复
热议问题