6

我正在使用一个简单GridLayout的动态添加按钮。

<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>

我正在使用这个 Java 代码来填充我的网格,除了 set Gravity 选项没有做任何事情之外,它一切正常。我已经尝试过 - 将 layout_width 更改为 XML 文件中的不同类型,添加重力GridLayout等,如本网站其他解决方案中所述。另一件需要注意的是,我是在片段内的异步任务中执行此操作的。基本上我想layout_gravity="fill_horizontal"实现在 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]);
        }
4

1 回答 1

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)

于 2014-07-31T13:08:14.453 回答