setLayoutParams overriding setGravity for layout



我的布局文件中有这个部分:

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

我的目标是设置 linearLayout 中项目的重力,然后以编程方式为整个 LinearLayout 添加边距。

这是我所拥有的:

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);,我的重力值设置正确。

为什么在将布局参数设置为我的布局后重力重置?

当你这样做时:

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

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

使用这个:

linearLayout_textBackground.setGravity(gravity);

在此之后:

linearLayout_textBackground.setLayoutParams(layoutParams);

或者在定义布局参数中定义布局重力。

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

android:layout_gravity="center"

那么你不需要这样做:

linearLayout_textBackground.setGravity(gravity);

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

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

这解决了问题。

最新更新