【问题标题】:SetGravity for GridLayout not workingGridLayout 的 SetGravity 不起作用
【发布时间】:2013-01-04 07:43:52
【问题描述】:

我正在使用一个简单的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 选项没有做任何事情之外,它一切正常。我试过 - 在 XML 文件中将 layout_width 更改为不同的类型,向GridLayout 等添加重力,如本网站其他解决方案中所述。另一件需要注意的是,我在 Fragment 内的异步任务中执行此操作。基本上我想实现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]);
        }

【问题讨论】:

  • 尽管我使用 button.setMaxWidth() 进行了妥协,但仍然没有找到答案。
  • 你可以这样做... LayoutParams param; lp = (LayoutParams) tagButtons[i].getLayoutParams(); lp.gravity = Gravity.FILL_HORIZONTAL; tagButtons[i].setLayoutParams(lp);

标签: android android-layout gravity grid-layout


【解决方案1】:

正如 Karan Mer 所说,您使用 GridLayout.LayoutParams 设置布局重力。

但要小心,在 Gridlayout 中,您必须在之前设置子项(在您的情况下为 Button)的 columnSpec / rowSpec:

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

只有这样

param.setGravity(Gravity.RIGHT);

如果在执行 setGravity 时 columnSpec / rowSpec 未定义,则重力不起作用...

即使你这样做:

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

重力不起作用...

正确的做法是:

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

我不知道是错误还是故意的。 (我使用的是 Android API 19)

【讨论】:

    猜你喜欢
    • 2014-07-19
    • 1970-01-01
    • 2012-04-26
    • 2015-11-30
    • 2018-12-30
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多