Android: GridView width not wrapping to content?

前端 未结 4 1758
广开言路
广开言路 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:37

    I know that this post is a bit outdated. But if someone needs a solution to this, this answer may come in handy.

    It is possible to set the view's width after screen measurement.

    To do this:

    Let your class implement the OnGlobalLayoutListener. The screen is measured when the onGlobalLayout method is called. We can do our magic here. GridView.getLayoutParams().width = ....

    edit: I wasn't very clear on how to add the onGlobalLayoutListener. See plugmind's post, he shows how to add it. Can't figure out how to get view/layout width/height

    Kind regards, Bram

    0 讨论(0)
  • 2021-01-13 15:42

    I think you should use android:layout_width="fill_parent" instead of android:layout_width="wrap_content" because wrap content use the minimum place it needs. On the other hand, fill_parent use all space needed. More over you should get rid of "android:columnWidth="70dp".

    0 讨论(0)
  • 2021-01-13 15:52

    It's certainly possible to set a fixed layout_width (in dp). Since the number of your columns is also fixed, could this be a workaround for you?

    0 讨论(0)
  • 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());    
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题