2013-03-07 65 views
2

我看到这种奇怪的行为,并想问问任何人是否找到解决方法。 我有一个简单的RelativeLayout与另一个布局里面。setLayoutParams混淆RelativeLayout

奇怪的行为发生在代码中。如果我从嵌套布局获取LayoutParams,并将其设置回它,它将更改布局的外观。似乎有些参数在这个过程中丢失了。下面是代码:

RelativeLayout v = (RelativeLayout)findViewById(R.id.group1); 

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(v.getLayoutParams()); 

v.setLayoutParams(lp); 

这个电话我期待一切保持原样后,但是,我失去了“layout_AlignParentRight”的效果(至少)。任何人都可以帮我理解为什么发生这种情况?

从实际的角度来看,我所需要的只是在运行时改变group1布局的宽度。所以我通过改变上面“lp”的宽度来做到这一点,它可以工作,但会弄乱对齐。因此,如果对改变布局大小而不影响其他属性的替代方法有任何建议,请加以注意。

布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="wrap_content"  
android:orientation="vertical"> 

    <RelativeLayout 
    android:id="@+id/group1" 
    android:layout_width="100dp" 
    android:layout_height="wrap_content"  
    android:orientation="vertical" 
    android:layout_alignParentRight="true"> 

     <TextView 
     android:layout_alignParentLeft="true" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Test"> 
     </TextView> 

    </RelativeLayout> 
</RelativeLayout> 
+0

你是从 “V” 得到的RelativeLayout PARAMS和设置PARAMS为 “V”。 ..? – drulabs 2013-03-07 18:20:18

回答

5

只是修改已经存在的,而不是实例化新的PARAMS:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)v.getLayoutParams(); 
params.width = myNewWidth; 
v.requestLayout(); 
+1

谢谢!这确实有用。并用这种方法setLayoutParams()也可以。我想知道为什么从现有对象的实例化LayoutParams丢失信息... – 2013-03-07 19:12:13