setLayoutParams 覆盖布局的 setGravity

setLayoutParams overriding setGravity for layout

我的布局文件中有此部分:

<RelativeLayout>
    <LinearLayout android:layout_width="match_parent"
            android:layout_height="wrap_content">
        <TextView></TextView>
        <TextView></TextView>
    </LinearLayout>
</RelativeLayout>

我的objective是在linearLayout里面设置item的gravity,然后编程给整个LinearLayout加上margin。

这是我的:

linearLayout_textBackground.setGravity(gravity); //where gravity is the int of the desired gravity

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                   RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
linearLayout_textBackground.setLayoutParams(layoutParams);
linearLayout_textBackground.requestLayout();

我想使用 layoutParams 设置边距,但是当我 运行 上面的代码时,我注意到我的重力值已被重置。但是,如果我注释掉 linearLayout_textBackground.setLayoutParams(layoutParams);,我的重力值设置正确。

为什么在我为布局设置LayoutParams 后重力会重置?

当你这样做时:

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
               RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

您正在为您的布局参数创建新参考,您在此处提及的参数将更改,其他未提及的参数将更改为默认值 android。如果你想改变重力,那么你需要在创建新的参数后改变它,比如:

使用这个:

linearLayout_textBackground.setGravity(gravity);

此后:

linearLayout_textBackground.setLayoutParams(layoutParams);

或者在定义layoutParams中定义你的layout gravity。

但推荐的重力设置方法是在 xml 内部,如下所示:

android:layout_gravity="center"

那你就不需要这样做了:

linearLayout_textBackground.setGravity(gravity);

感谢@M.Saad Lakhan 的回答,我注意到我正在创建参数的新引用。所以我最终做的是获取布局的实际参数:

RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) 
                    linearLayout_textBackground.getLayoutParams();

这解决了问题。