setLayoutParams覆盖布局

时间:2017-11-14 10:26:40

标签: android android-layout android-linearlayout android-relativelayout

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

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

为什么在setLayoutParams到我的布局后重力重置?

2 个答案:

答案 0 :(得分:1)

执行此操作时:

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

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

使用此:

linearLayout_textBackground.setGravity(gravity);

之后:

linearLayout_textBackground.setLayoutParams(layoutParams);

或定义layoutParams中的布局重力。

但是建议您设置引力的方法是在xml中,如下所示:

android:layout_gravity="center"

然后你不需要这样做:

linearLayout_textBackground.setGravity(gravity);

答案 1 :(得分:0)

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

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

这解决了问题。