Android: GridView width not wrapping to content?

前端 未结 4 1763
广开言路
广开言路 2021-01-13 15:15

I am trying to display a GridView in a Dialog. Despite all my efforts, the GridView width grows to the entire screen, instead of wrapping to the columns. The layout and an

4条回答
  •  臣服心动
    2021-01-13 15:54

    Had the same problem... I solved it with overridden onMeasure()

    public class GridViewEx extends GridView {
    
        private int mRequestedNumColumns = 0;
    
        public GridViewEx(Context context) {
            super(context);
        }
    
        public GridViewEx(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public GridViewEx(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        @Override
        public void setNumColumns(int numColumns) {
            super.setNumColumns(numColumns);
    
            if (numColumns != mRequestedNumColumns) {
                mRequestedNumColumns = numColumns;
            }
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    
            if (mRequestedNumColumns > 0) {
                int width = (mRequestedNumColumns * getColumnWidth())
                        + ((mRequestedNumColumns-1) * getHorizontalSpacing())
                        + getListPaddingLeft() + getListPaddingRight();
    
                setMeasuredDimension(width, getMeasuredHeight());    
            }
        }
    }
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题