Android: GridView width doesn't apply to content?

I am trying to display a gridview in a dialog. In spite of all my efforts, the width of the GridView increases in full screen, not in columns. The layout and image depicting the problem are below (I set the background color for the GridView to illustrate the problem).

<?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/colorgridview" android:background="#FF00CCBB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:numColumns="4" android:verticalSpacing="5dp" android:horizontalSpacing="5dp" android:columnWidth="70dp" android:stretchMode="none" /> 

enter image description here

+4
source share
4 answers

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

You can set the display width after measuring the screen.

For this:

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

edit: I did not quite understand how to add onGlobalLayoutListener. See the message "plugmind post", it shows how to add it. Unable to figure out how to get width and height of view / layout

Regards, Bram

+1
source

I think you should use android:layout_width="fill_parent" instead of android:layout_width="wrap_content" , because the contents of the covers use the minimal space that it needs. On the other hand, fill_parent uses all the necessary space. Moreover, you should get rid of "android:columnWidth="70dp".

0
source

Of course, you can set a fixed layout_width (in dp). Since the number of your columns is also fixed, can this be a workaround for you?

0
source

There was the same problem ... I solved this 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
source

Source: https://habr.com/ru/post/1347922/


All Articles