You want the columnWidth be 60dp, and using the auto_fit num_columns , the GridView value measures the number of columns. In your adapter, you force the size of the element, which then does not match the width and number of columns of the GridView .
Here is one way to calculate the actual columnWidth that will fit. Not 100% sure that the math is right here, but I hope this can give you the opportunity to solve your problem.
If you want the elements to be rectangles, you could pass the calculated width to the adapter and use for the width and height of the view layout.
Activity:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final GridView gv = (GridView) findViewById(R.id.all_cards_grid_view); gv.post(new Runnable() { @Override public void run() { gv.setColumnWidth((gv.getWidth() - (gv.getNumColumns() * gv.getHorizontalSpacing()) - gv.getHorizontalSpacing() * 2) / gv.getNumColumns()); gv.setAdapter(new TestAdapter(MainActivity.this)); } }); } public class TestAdapter extends BaseAdapter { private static final int CARD_PADDING = 10; private Context mContext; public TestAdapter(Context context) { mContext = context; } @Override public View getView(final int position, View convertView, ViewGroup parent) { TextView textView; if (convertView == null) { textView = new TextView(mContext); textView.setPadding(CARD_PADDING, CARD_PADDING, CARD_PADDING, CARD_PADDING);
Xml:
<GridView android:id="@+id/all_cards_grid_view" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingTop="5dp" android:paddingBottom="5dp" android:background="#30000000" android:columnWidth="60dp" android:numColumns="auto_fit" android:horizontalSpacing="0dp" android:stretchMode="spacingWidthUniform" android:verticalSpacing="5dp"/>
Niko
source share