Search code examples
androidandroid-layoutgridviewandroid-linearlayoutgravity

Center view in android after changing its width properties


I'm changing the width of a grid view based on its column width and number of columns (which works):

gridView.setLayoutParams(new LinearLayout.LayoutParams(gridManipulation.getColumnWidth() * (int)Math.sqrt(str.length) + 10, LayoutParams.FILL_PARENT));
gridView.setGravity(Gravity.CENTER);

I've tried re-centering it in the parent view but its not working, does anyone know why, its still centred as if it still has the width parameters before my dynamic change.

enter image description here


Solution

  • Set the Gravity as LayoutParams property then set that LayoutParams to your GridView as follows...

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(gridManipulation.getColumnWidth() * (int)Math.sqrt(str.length) + 10, LayoutParams.FILL_PARENT);
    params.gravity = Gravity.CENTER;
    
    gridView.setLayoutParams(params);