SetGravity for GridLayout not working
Asked Answered
D

1

6

I am using a simple GridLayout to which I'm adding buttons dynamically.

<GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/tagGridLayout"
android:background="@color/white"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:columnCount="3"
>
</GridLayout>

And I am using this Java code to fill my grid which is all working fine except that the set Gravity option doesn't do anything. I've tried - changing layout_width to different types in the XML file, adding gravity to the GridLayout etc. as mentioned in other solutions on this site. Another thing to note is that I am doing this in an Async task inside a Fragment. Basically I want to achieve what layout_gravity="fill_horizontal" achieves in the XML.

tagButtons = new Button[trendingTagsCount];
        for(int i=0;i<trendingTagsCount;i++)
        {
            tagButtons[i] = new Button(getActivity());
            //tagButtons[i].setLayoutParams(new LayoutParams(Gravity.FILL_HORIZONTAL));
            tagButtons[i].setText(getTagsList.get(i).tag);
            tagButtons[i].setGravity(Gravity.FILL_HORIZONTAL);
            tagButtonGrid.addView(tagButtons[i]);
        }
Desiraedesire answered 21/1, 2013 at 9:16 Comment(2)
Still haven't found the answer though I managed a compromise using button.setMaxWidth() and the same for Height.Desiraedesire
you can do something like this... LayoutParams param; lp = (LayoutParams) tagButtons[i].getLayoutParams(); lp.gravity = Gravity.FILL_HORIZONTAL; tagButtons[i].setLayoutParams(lp);Adora
O
5

As Karan Mer said you set the Layout Gravity with GridLayout.LayoutParams.

But be careful, in Gridlayout you have to set the columnSpec / rowSpec of the Children (in your case the Button) before:

param.columnSpec = GridLayout.spec(0);
param.rowSpec = GridLayout.spec(0);

and only then

param.setGravity(Gravity.RIGHT);

if columnSpec / rowSpec is UNDEFINED when you do setGravity, gravity doesn't work...

Even if you do:

param.setGravity(Gravity.RIGHT);
param.columnSpec = GridLayout.spec(0);
param.rowSpec = GridLayout.spec(0);

Gravity doesn't work...

The right way is:

param.columnSpec = GridLayout.spec(0);
param.rowSpec = GridLayout.spec(0);
param.setGravity(Gravity.RIGHT);

I don't know if is a bug or a deliberate thing. (I'm using Android API 19)

Orthocephalic answered 31/7, 2014 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.