代码之家  ›  专栏  ›  技术社区  ›  riadrifai

setLayoutParams覆盖布局的setGravity

  •  0
  • riadrifai  · 技术社区  · 8 年前

    我的布局文件中有以下部分:

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

    这就是我所拥有的:

    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设置到布局后重力会重置?

    2 回复  |  直到 8 年前
        1
  •  1
  •   Muhammad Saad Rafique    8 年前

    执行此操作时:

    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\u text背景。setGravity(重力);
    
        2
  •  0
  •   riadrifai    8 年前

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

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

    这解决了问题。