以编程方式设置LinearLayout的子项的权重

时间:2014-04-17 19:59:47

标签: android xml android-layout android-linearlayout

我有一个垂直的LinearLayout LL_p,其中有两个子级为LinearLayouts LL_1和LL_2,而这些子级又有自己的子级。根据LL_1和LL_2的可见内容,我想动态更改LL_p中的相对权重。我已经有了一个xml布局,里面有很多我不想丢失的细节,所以我只需要对权重进行增量更改。我怎么做?这是我的xml

…
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=“0.2”
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/ll_1”
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.55"
            android:background="@drawable/some_image”
            android:orientation="vertical" >

            <!—- a number of includes —>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/ll_2”
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.45"
            android:layout_marginBottom="@dimen/dim_1”
            android:background="@color/some_color”
            android:orientation="horizontal" >

            <!—- a number of children —>
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

所以在java活动类中,我想我需要以下方法,但我需要帮助来完成它。请注意,我没有实例化新的布局参数,因为这会导致我丢失我的xml布局细节;相反,我使用getLayoutParams从xml中获取一组。那么如何对所获得的布局进行重量调整?

private void adjustMYLayout(boolean flip) {
    LayoutParams layout1 = mLL1.getLayoutParams();
    LayoutParams layout2 = mBLL2.getLayoutParams();
    //now what?
    if(flip) {//set one weight system
    }else {
        //set other weight system
    }
}

@nKn更新

private void adjustMYLayout(boolean flip) {

  if (flip) {
    mLL1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.8f));
         mLL2.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.2f));
  } else {
    mLL1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.55f));
    mLL2.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT, 0.45f));
  }
}

1 个答案:

答案 0 :(得分:4)

您可以通过声明LinearLayout.LayoutParams对象

来实现这一目标
tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));

第三个参数(1f)是布局的权重(在这种情况下为1(f代表float))。