如何在我的视图中更改layout_weight(以编程方式)

时间:2014-07-25 10:51:14

标签: android android-layout view android-layout-weight

如何使用Java代码从XML更改layout_weight对象的View?我已经在下面尝试了最后一件事。 vynosy是我要设置的值的属性。

View hospVyslLineAppColor = (View) view.findViewById 
                            (R.id.hospodarsky_vysledok_line_appcolor);

hospVyslLineAppcolor.setLayoutParams(new LinearLayout.LayoutParams(
            LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT,
            Math.abs((float)vynosy)));

我的XML:

<View
     android:id="@+id/hospodarsky_vysledok_line_appcolor"
     android:layout_width="match_parent"
     android:layout_height="20dp"
     android:layout_weight="69382"
     android:background="#a8a8a8" />

3 个答案:

答案 0 :(得分:1)

您可以将此用于linearlayout

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT;  
params.weight = 1;

答案 1 :(得分:0)

您需要了解Layout_weights的工作原理。仅当您有多个视图时,这些才有效。您的代码是正确的,只需添加一个视图。两者都以线性布局声明。您需要应用权重的布局。

 View hospVyslLineAppColor = (View) view.findViewById (R.id.hospodarsky_vysledok_line_appcolor);

        hospVyslLineAppcolor.setLayoutParams(new LinearLayout.LayoutParams(
        LayoutParams.MATCH_PARENT,
        LayoutParams.WRAP_CONTENT,
        Math.abs((float)vynosy))); // see to it the value of vynosy is less than 1

 View hospVyslLineAppColor1 = (View) view.findViewById (R.id.hospodarsky_vysledok_line_appcolor);

        hospVyslLineAppColor1.setLayoutParams(new LinearLayout.LayoutParams(
        LayoutParams.MATCH_PARENT,
        LayoutParams.WRAP_CONTENT,
        (1 - Math.abs((float)vynosy)))); // Will complement the weight

重新使用您的XML文件:

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

          <!-- layout_height is 0dp as height is to be set by weight factor -->
           <View
              android:id="@+id/hospodarsky_vysledok_line_appcolor"
              android:layout_width="match_parent"
              android:layout_height="0dp" 
              android:layout_weight="0.4"
              android:background="#a8a8a8" />

          <!-- layout_height is 0dp as height is to be set by weight factor -->
           <View
              android:id="@+id/hospodarsky_vysledok_line_appcolor1"
              android:layout_width="match_parent"
              android:layout_height="0dp"
              android:layout_weight="0.6"
              android:background="#a8a8a8" />
        </LinearLayout>

答案 2 :(得分:0)

我认为这会对你有帮助...... Set Width Programatically on SO

但我认为不可能以编程方式更改此属性,但只能在新属性中设置新的布局(通常是查看)。