2013-03-07 38 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