Note that there are some explanatory texts on larger screens.

plurals
  1. POAndroid: how to force GridView width to wrap_content?
    text
    copied!<p>My GridView contains columns of fixed width, with fixed horizontal spacing. If there are not enough columns to fill the screen horziontally, I would like my GridView's width to wrap to its contents, and to center vertical in the screen.</p> <p>However, regardless of the number of columns I use, the GridView's width grows to fill the screen. The attached image shows this, where the green GridView fills the screen horizontally, despite having only 3 columns and its width being set to "wrap_content". </p> <pre><code>public class Temp extends Activity { private GridView grid; private int columnWidth = 80; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = getLayoutInflater().inflate(R.layout.gridview, null); grid = (GridView) view.findViewById(R.id.grid); grid.setColumnWidth(columnWidth); grid.setAdapter(new GridAdapter()); setContentView(view); } class GridAdapter extends BaseAdapter { public GridAdapter() { } public int getCount() { return 3; } public Object getItem(int position) { return null; } public long getItemId(int position) { return position; } public View getView (int position, View convertView, ViewGroup parent) { View ret; if (convertView == null) { ret = new ImageView(Temp.this); ret.setLayoutParams(new GridView.LayoutParams(columnWidth, 100)); ret.setBackgroundColor(Color.WHITE); } else { ret= convertView; } return ret; } } } &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="#FF0000" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;GridView android:id="@+id/grid" android:background="#00FF00" android:layout_centerInParent="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:numColumns="auto_fit" android:verticalSpacing="2dip" android:horizontalSpacing="2dip" android:stretchMode="columnWidth" android:gravity="center"&gt; &lt;/GridView&gt; &lt;/RelativeLayout&gt; </code></pre> <p><img src="https://i.stack.imgur.com/whRJb.png" alt="enter image description here"></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload