setLayoutParams搞砸了RelativeLayout

Den*_*s K 2 layout android relativelayout layoutparams

我看到这种奇怪的行为,并想问是否有人找到了解决方法.我有一个简单的RelativeLayout,里面有另一个布局.

奇怪的行为发生在代码中.如果我从嵌套布局中获取LayoutParams并将其设置回它,则会改变布局的外观.似乎某些参数在此过程中丢失了.这是代码:

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

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

v.setLayoutParams(lp);
Run Code Online (Sandbox Code Playgroud)

在这个调用之后,我期待一切都保持不变,但是,我正在失去"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>
Run Code Online (Sandbox Code Playgroud)

kco*_*ock 6

只需修改已存在的参数,而不是实例化新参数:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)v.getLayoutParams();
params.width = myNewWidth;
v.requestLayout();
Run Code Online (Sandbox Code Playgroud)